# Proper definition of eltype for custom iterator

**URL:** https://discourse.julialang.org/t/proper-definition-of-eltype-for-custom-iterator/21903
**Category:** General Usage
**Created:** [March 15, 2019, 8:23am UTC](https://discourse.julialang.org/t/proper-definition-of-eltype-for-custom-iterator/21903 "2019-03-15T08:23:19Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)
#### Post date: [March 15, 2019, 8:58am UTC](https://discourse.julialang.org/t/proper-definition-of-eltype-for-custom-iterator/21903/2 "2019-03-15T08:58:36Z")

</div>

I would write it as:

```julia
struct Squares{T <: Real}
    count::Int
end

Base.iterate(s::Squares{T}, state=1) where {T} = state > s.count ? nothing : (T(state^2), state+1)
Base.length(s::Squares) = s.count
Base.eltype(::Type{Squares{T}}) where {T} = T

```

And the code you executed would be written as:

```julia
for i in Squares{UInt8}(4) println(i) end

collect(Squares{Rational{Int64}}(3))

9 in Squares{Float32}(3)

```

---

_[View the full topic](https://discourse.julialang.org/t/proper-definition-of-eltype-for-custom-iterator/21903)._
