# With struct do

**URL:** <https://discourse.julialang.org/t/with-struct-do/41341>\
**Category:** New to Julia\
**Tags:** question\
**Created:** [June 13, 2020, 9:22pm UTC](https://discourse.julialang.org/t/with-struct-do/41341 "2020-06-13T21:22:19Z")\
**Posts on this page:** 1\
**Showing post:** 12

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [June 14, 2020, 6:04pm UTC](https://discourse.julialang.org/t/with-struct-do/41341/12 "2020-06-14T18:04:14Z")

</div>

If you’re willing to explicitly mark which symbols should be treated as fields, then this is easier to implement. Here’s a macro which will replace all expressions of the form `&a` with `container.a`:

```julia
julia> using MacroTools: postwalk

julia> macro with(container, expr)
         esc(postwalk(expr) do ex
           if @capture(ex, &field_)
             :(($container).$field)
           else
             ex
           end
         end)
       end
@with (macro with 1 method)

```

Usage:

```julia
julia> mutable struct Bar
           field1
           field2
           field3
       end

julia> b = Bar(1, 2, 0)
Bar(1, 2, 0)

julia> @with b begin
         &field3 = &field1 + &field2
       end
3

julia> b
Bar(1, 2, 3)

```

This implementation doesn’t have any problem with local variables which happen to match the names of fields, since the user is responsible (by adding `&`) for explicitly marking which symbols should be treated as fields:

```julia
julia> field1 = π
π = 3.1415926535897...

julia> @with b begin
         # The left-hand side is unambiguously `b.field1` 
         # and the right-hand side is unambiguously
         # the local variable `field1`.
         &field1 = field1
       end
π = 3.1415926535897...

julia> b
Bar(π, 2, 3)

```

---

_[View the full topic](https://discourse.julialang.org/t/with-struct-do/41341)._
