Learning Julia by (ab)using constructor

Welcome!

You can use @with_kw from Parameters.jl to define your default values like:

@with_kw mutable struct C
  id::String
  speak::Function = (word) -> println(id, word)
end

(I’ve shortened your example a bit, but hopefully the idea makes sense).

I guess you could use it for that–it’s extremely unusual to define anything inside the struct other than its fields, and I don’t think I’ve ever seen it done in Julia code in the wild. It’s not something I’ve ever needed, particularly because as soon as you start putting your behavior outside of your structs, it doesn’t really make sense.

4 Likes