Hi.
I have the following problem/question. I have a struct
struct foo{T<:Integer, U<:Real} <: AbstractGraph{T}
bar1::T
bar2::U
end
Now, I want to create an instance of foo, where I explicitly define the type U but infer the type T from the arguments. I tried
function foo{U}(...) where {U<:Real}
# do some stuff here and get T
foo{T,U}(bar1, bar2)
end
But this errored with asking for T. Now, what is the right way to construct foo with only passing U as a type?
EDIT1: See the marked answer and have a look at this thread as well: https://discourse.julialang.org/t/how-to-correctly-define-and-call-templated-parametric-methods-using-the-new-where-syntax
Something like that?
function foo(::Type{U}, bar2) where {U<:Real}
# do some stuff here and get T
T = typeof(bar2)
bar1 = zero(U)
foo{T,U}(bar1, bar2)
end
Hi @Henrique_Becker,
thanks, that was what I was looking for!
I noticed just now that this is basically the first doubt I asked in Discourse.
So the inquirer is now the replier. The cycle begins anew.
Very good! Reading through your linked thread leaves me with another question. What is the difference between below definitions of foo
foo(::Type{U}) where {U<:Real}
and
foo(U::Type)
besides that U can by any type in the second example und only a subtype of real in the first?
There is no difference. Actually, if you define foo at the REPL, you will see that after the second definition, there is still only one method!
julia> foo(::Type{U}) where U = 1
foo (generic function with 1 method)
julia> foo(U::Type) = 100
foo (generic function with 1 method)
That’s interesting. So, why are there two different syntax’?
As in your example, writing Type{T} where T gains you access to the type parameter either for dispatch purposes (T <: Real) or to use later inside your function.
that makes sense! Great, thanks!