Search code examples
structmacrosjuliaoperators

In Julia, how to define operator for more than 2 structs?


In Julia, I have my own struct, say MyNumber. I would like to define an operator, e.g. the product operator *, for my struct. The following is what I tried.

struct MyNumber
    name::String
    value::Int
end

x1 = MyNumber("postive", 4)
x2 = MyNumber("postive", 3)

# define product operator for MyNumber
a::MyNumber * b::MyNumber = MyNumber("no_name", a.value + b.value)

y = x1*x2
println(y) # ok here, output: MyNumber("no_name", 7)

It works very well. However, when I try I apply the product for more than 2 inputs, e.g. z=x1*x2*x1*x2*x2, I got error. How do I deal with such case?


Solution

  • Here is the correct way of defining the * operator for a custom data type:

    import Base.:*
    
    struct MyNumber
        name::String
        value::Int
    end
    
    x1 = MyNumber("postive", 4)
    x2 = MyNumber("postive", 3)
    
    # define product operator for MyNumber
    Base.:*(a::MyNumber, b::MyNumber)::MyNumber = MyNumber("no_name", a.value + b.value)
    
    y = x1*x2
    println(y) # ok here, output: MyNumber("no_name", 7)
    

    The operator should be imported from the Base package explicitly.

    Edit: Since I have used the Base.:* in the method definition, it is not needed to import the operator explicitly as mentioned below.