# Is accessing the fields of a struct a good julia-style?

**URL:** https://discourse.julialang.org/t/is-accessing-the-fields-of-a-struct-a-good-julia-style/23623
**Category:** General Usage
**Created:** [April 28, 2019, 5:34pm UTC](https://discourse.julialang.org/t/is-accessing-the-fields-of-a-struct-a-good-julia-style/23623 "2019-04-28T17:34:26Z")
**Posts on this page:** 1
**Showing post:** 3

<div class="post-metadata">

### Author: ![dfdx](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dfdx/32/120_2.png) [@dfdx](https://discourse.julialang.org/u/dfdx)
#### Post date: [April 28, 2019, 7:19pm UTC](https://discourse.julialang.org/t/is-accessing-the-fields-of-a-struct-a-good-julia-style/23623/3 "2019-04-28T19:19:52Z")

</div>

Julia lets you define accessors later, e.g. if you rename the fields, you can still provide old names using `getproperty()`:

```julia
struct Foo{T}
  new_data::Vector{T}
  new_ptrs::Vector{Int}
end

function Base.getproperty(foo::Foo, p::Symbol)
    if p == :data
        return getfield(foo, :new_data) # getfield() reads fields directly and it cannot be overloaded
    elseif p == :ptrs
        return getfield(foo, :new_ptrs)
    else
        return getfield(foo, p)
    end
end

f = Foo([1,2,2,5,1,7],[1,3,6,7])
println(f.data)
println(f.ptrs)

```

Note that Julia compiler is smart enough to still translate simple `getproperty()` calls into direct field pointers:

```julia
julia> using BenchmarkTools

julia> @btime $f.data;
  1.753 ns (0 allocations: 0 bytes)

julia> @btime $f.new_data;
  1.754 ns (0 allocations: 0 bytes)

```

There’s also `Base.setproperty!()` for property mutation.

---

_[View the full topic](https://discourse.julialang.org/t/is-accessing-the-fields-of-a-struct-a-good-julia-style/23623)._
