# How to make a struct support subsetting elements 'recursively'

**URL:** https://discourse.julialang.org/t/how-to-make-a-struct-support-subsetting-elements-recursively/43344
**Category:** New to Julia
**Tags:** question
**Created:** [July 19, 2020, 6:56pm UTC](https://discourse.julialang.org/t/how-to-make-a-struct-support-subsetting-elements-recursively/43344 "2020-07-19T18:56:42Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![mkarikom](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mkarikom/32/7096_2.png) [@mkarikom](https://discourse.julialang.org/u/mkarikom)
#### Post date: [July 19, 2020, 6:56pm UTC](https://discourse.julialang.org/t/how-to-make-a-struct-support-subsetting-elements-recursively/43344/1 "2020-07-19T18:56:42Z")

</div>

Suppose I have the following:

```julia
struct mystuff
  x::Array{Float64,1}
  y::Array{Float64,1}
  mystuff(n) = begin
    s = new(Array{Float64,1}(undef,n),Array{Float64,1}(undef,n))
    return s
  end
  mystuff(x,y) = begin
    s = new(x,y)
    return s
  end
end

check = mystuff([1,2,3],[8,9,10])

```

How do I make this support subsetting like `check2=check[<indexes>]` so that the following happens:

```julia
julia> check2=check[1:2]
julia> check2.x
2-element Array{Float64,1}:
 1.0
 2.0
julia> check2.y
2-element Array{Float64,1}:
 9.0
 10.0

```

---

<div class="post-metadata">

### Author: ![a5vzener](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/a5vzener/32/16257_2.png) [@a5vzener](https://discourse.julialang.org/u/a5vzener)
#### Post date: [July 19, 2020, 7:48pm UTC](https://discourse.julialang.org/t/how-to-make-a-struct-support-subsetting-elements-recursively/43344/2 "2020-07-19T19:48:44Z")

</div>

As one solution, you could override Base.getindex:

> julia\> import Base: getindex
> 
> julia\> getindex(s::mystuff, i) = mystuff(s.x[i], s.y[i])  
> getindex (generic function with 545 methods)
> 
> julia\> check = mystuff([1,2,3],[8,9,10])  
> mystuff([1.0, 2.0, 3.0], [8.0, 9.0, 10.0])
> 
> julia\> check[1:2]  
> mystuff([1.0, 2.0], [8.0, 9.0])

This is a typical Julia pattern. Use the type system to create specific behavior and override Base or other functions (i.e. add new methods of those functions) locally to support your types.

---

<div class="post-metadata">

### Author: ![mkarikom](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mkarikom/32/7096_2.png) [@mkarikom](https://discourse.julialang.org/u/mkarikom)
#### Post date: [July 19, 2020, 8:04pm UTC](https://discourse.julialang.org/t/how-to-make-a-struct-support-subsetting-elements-recursively/43344/3 "2020-07-19T20:04:30Z")

</div>

perfect, thanks
