How is a string assigned to a struct in this Julia code?

Viewed 125

I'm looking at the this thread

I'm trying to understand the following line of code:

struct Foo end
(::Type{Float64})(::Foo) = "not a Float64"

It seems like it assigns a string to a variable of type Foo, but I don't see any variable declaration on the left-hand-side.

What is going on?

1 Answers

There's a few things going on here.

  1. The line is a method, not a variable assignment. f(x) = "blah" is one-line syntax for
function f(x)
  "blah"
end
  1. The (::Foo) part is actually 1 annotated argument for the method. An argument's name can be omitted, you just can't use the argument in the method body because no variable references it. The argument only dispatches the method. For example, f(::Foo) = "blah" would work for f(Foo()) but not f(Bar()).

  2. The (::Type{Float64}) part instead of a method name indicates this is a functor. (f::F)(x) = x*f.suffix means that instances of struct F can be called like a method F(".net")("something"). The name f isn't a method name and will not exist for you to use like one, it's there to reference the instance of F to be used in the method. The name can be omitted if it's not used in the method (::F)(x) = x*".com".

  3. Type{Float64} is a type whose only instance is Float64, so this means that you can only use this method by calling Float64(Foo()). It seems to me that defining a method Base.Float64(::Foo) = "not a Float64" would be equivalent, I don't actually know why they opted for functor syntax.

When you see annotations surrounded by parentheses, the annotation can only belong to whatever is in the parentheses and to the left. f::Foo means f is annotated with Foo, f(::Foo) means an anonymous argument is annotated with Foo.

Related