I met code as follow, anyone can give an syntactic explanation?
mutable struct WriteClosure{T, KW}
buf::T
end
function (f::WriteClosure)(i, nm, TT, v; kw...)
end
I met code as follow, anyone can give an syntactic explanation?
mutable struct WriteClosure{T, KW}
buf::T
end
function (f::WriteClosure)(i, nm, TT, v; kw...)
end
If an object of type WriteClosure
is called, then that function is called.
Example:
> wc = WriteClosure{T1, T2}(buf)
> wc(i, nm, TT, v) # calling the defined function
Thanks!
Well, is it a common syntax, and what’s the name ?
The relevant part of the Julia docs is here.
I’d say they are a commonly used feature of the language. Sometimes, they are referred to as “Functor” or “callable struct.”
Method dispatch does not treat function-like objects differently from typical functions. Say in the call foo(a, b)
, the dispatch is occurring over the types of the callable and the arguments (foo, a, b) isa Tuple{typeof(foo), typeof(a), typeof(b)}
. In fact, you can add methods to foo
with the same syntax (::typeof(foo))(c) = "blah"
, but typical functions are conveniently given a const
name and extra behaviors via subtyping Function
. If the struct
type isn’t singleton (has no fields), then you can’t give any of its instances a const
name, but otherwise you could opt into much of function’s behaviors.
Thanks!
I should read the docs more often.