Hellow, how can i write a function like this:
vector_data_type = [
Int64,
Int32,
Int16,
]
foo(T) where T # in vector_data_type
Hellow, how can i write a function like this:
vector_data_type = [
Int64,
Int32,
Int16,
]
foo(T) where T # in vector_data_type
With a for loop and @eval
:
julia> for T in (Int64, Int32, Int16)
@eval foo(::$T) = string($T)
end
julia> foo(1)
"Int64"
julia> foo(Int16(1))
"Int16"
Or perhaps you meant a case where the source is the same for all the methods and doesn’t requires any interpolation/eval. You can use a Union for many cases like that.
julia> bar(::T) where T <: Union{Int64, Int32, Int16} = string(T)
bar (generic function with 1 method)
julia> bar(1)
"Int64"
julia> bar(Int16(1))
"Int16"
julia> bar(Int8(1))
ERROR: MethodError: no method matching bar(::Int8)
You mean to define such a function?
foo(::Type{T}) where T<:Union{Int64,Int32,Int16}
but I would guess you’re actually looking for Integer
(which is a supertype of all of those, but may also encapsulate other integer types)