Two type composite struct construction

I have the following problem/question. I have a struct

struct foo{T<:Integer, U<:Real} <: AbstractGraph{T}

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)

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:

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)

Hi @Henrique_Becker,

thanks, that was what I was looking for!

1 Like

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}



besides that U can by any type in the second example und only a subtype of real in the first?

1 Like

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’?

1 Like

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!

1 Like