How hard would it be to support getters and setters on structs?

84 views
Skip to first unread message

Thiago Majesk Goulart

unread,
Jul 8, 2025, 12:48:51 PMJul 8
to elixir-lang-core
This is more of a question than a proposal, and I don't actually know how viable it would be in reality. But today we can implement the access behaviour for structs, which can be really (really, really) useful in cases where you are dealing with rich data types.

I don't remember if this has been discussed in the forums before, so I would like to know if expanding on the syntax sugar to have accessors has ever been considered.

Maybe having something like a put/2 callback is a bit out of the scope for the access behaviour itself, and I'm sure this would pose some design challenges, like how to resolve for struct's static access and so on.

Anyways, I'm curious if the core team has considered something like this or if there are any plans to pursue a version of this in the future. My best.

Wojtek Mach

unread,
Jul 8, 2025, 2:09:03 PMJul 8
to elixir-l...@googlegroups.com
Do you mean `struct.field` would be a function call? Or `struct.field()` would desugar to something else? And what about setters, how would calling them look like? Maybe I’m to hang up on the syntax but I’m really curious what you’re thinking about.

FWIW you can make it so that this runs arbitrary call

    put_in(alice[:email], “al...@example.com”)

By defining get_and_update/3 on your struct.

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/elixir-lang-core/f7e3c66d-7de7-4d32-9df3-96d019b65ed2n%40googlegroups.com.

Message has been deleted
Message has been deleted

Thiago Majesk Goulart

unread,
Jul 11, 2025, 6:44:37 AMJul 11
to elixir-lang-core
TBH, I don't have a clear idea in my head, so that's why I'm not proposing a specific syntax for it... I'm just finding it increasingly useful to have it when dealing with rich data types. 
But let's imagine we are expanding the Access behaviour functionality (hypothetically). I would assume that `struct.field` and `struct[:field]` would need to be somewhat equivalent for this to work.
This means that things like `%{struct | field: value}`, `Map.put(struct, :field, value)` and `put_in(struct, [:field, value])` would also need to "resolve" to function calls (I guess)!?

In my mind, the "problem" with the Access behaviour today is that you need to be aware of a specific syntax that you can easily bypass.
I'm imagining that making those function calls would have some cost to it, but it might be a good tradeoff to have in an opt-in feature.
Reply all
Reply to author
Forward
0 new messages