Search code examples
juliafunctor

How to add the bang character to functors?


By convention, we add a bang character ! to any function name that mutates its arguments, so for the following code example, should we add a ! to the functor name?

mutable struct Foo
    a::Int
end

(foo::Foo)(val) = foo.a = val

f = Foo(1)  # f.a = 1
f(10)       # f.a = 10

In short, is it possible to call the last line as f!(10)? I am just curious. Thanks.


Solution

  • The call here is just the same as the name of your variable. So if you want it to contain a !, you will have to name your variable f!:

    julia> f! = Foo(1)  # f.a = 1
    Foo(1)
    
    julia> f!(4)
    4
    

    There is nothing magical about the ! character, it's just part of the identifier. So you have to put the ! inside the actual name, exactly like you do with functions.