Search code examples
juliavariant

Variant like in C++ for Julia


How can I use use something like variant (which is in C++) in Julia?

In C++, I can do something like this

variant<int, float> value;

How can I do the same thing in Julia for a parameter of a function?

function func(??)
    # something
end

Sorry if it does not convey what I want to do.


Solution

  • You can use union types to do the same.

    function func(x::Union{Int, AbstractFloat})
        x + 1
    end
    

    Note that C++ std::variant is a tagged union, so you can always ask "which" variant it is, whereas a Julia union is a proper set union. Pragmatically, that means that in std::variant<int, int>, you can distinguish between a "left int" and a "right int", but a Union{Int, Int} really is just an Int. There's no way to tell which "side" it came from. To emulate the exact tagged union behavior, you'll need to make some custom structs to represent each case.

    struct LeftInt
        value :: Int
    end
    
    struct RightInt
        value :: Int
    end
    
    function func(x::Union{LeftInt, RightInt})
        # ... Check whether x is a LeftInt or not ...
    end
    

    but, in Julia, you often don't need this, and if you do then it's generally smarter to work with generic functions to do your dispatching anyway.