Dispatching on struct fields

Hello everyone, I am writing two libraries (let’s say A and B) which should work together, but ideally either should know about other’s existence. I thought I had worked everything out by making use of multiple-dispatch with struct fields, but seems it works differently as I expected. The essential example looks as follows:

module TestModule

struct Foo
    bar
end

testhello(foo::Foo) = hello(foo.bar)

end

struct Buzz
    bizz
end

hello(buzz::Buzz) = println("$(buzz.bizz)")


mybuzz = Buzz("Hello")
# Test hello
hello(mybuzz)
# Test testhello
TestModule.testhello(mybuzz)

Is it an expected behaviour or a bug?

TestModule doesn’t know about the hello function which is defined outside of it.

Yes, that is the problem. I expeceted that since the TestModule would know about the type Buzz the methods for that type would follow. Is it appropriate to add another field to struct for letting TestModule to know about the hello method:

module TestModule

struct Foo
    bar
    hello
end

hello() = nothing 

testhello(foo::Foo) = foo.hello(foo.bar)

end

struct Buzz
    bizz
end


hello(buzz::Buzz) = println("$(buzz.bizz)")

mybuzz = Buzz("Hello")
# Test hello
hello(mybuzz)
# Test testhello
myfoo = TestModule.Foo(mybuzz,hello)
TestModule.testhello(myfoo)

No, you’d typically want to import or export a hello function either from TestModule or into TestModule.

2 Likes