Home > Back-end >  Is it possible to declare a general reference to any struct in Julia?
Is it possible to declare a general reference to any struct in Julia?

Time:09-17

I want to known if it is possible to implement a general reference inside a struct. The code is :

struct Foo1
  ia :: Int
end


struct Foo2{UNKNOWNTYPE}
  ref :: UNKNOWNTYPE
  ib :: Int
  
  function Foo2{UNKNOWNTYPE}(ref::UNKNOWNTYPE,ib::Int)
    o = new{UNKNOWNTYPE}(ref,ib) 
    return o
  end
end

foo1 = Foo1();
foo2 = Foo2{Foo1}(foo1,1)

In the above code, the type of variable ref in struct Foo2 is undetermined until running time. The above code does not work and it shows : "LoadError("main.jl", 6, UndefVarError(:UNKNOWNTYPE))".

CodePudding user response:

You're basically just missing a where UNKNOWNTYPE in your constructor definition. I'd recommend using a outer constructor for Foo2 like so

julia> struct Foo1
         ia::Int
       end

julia> struct Foo2{T}
         ref::T
         ib::Int
       end

julia> Foo2(ref::T, ib::Int) where T = Foo2{T}(ref, ib)
Foo2

julia> Foo2(Foo1(1), 1)
Foo2{Foo1}(Foo1(1), 1)

but an inner constructor works too:

julia> struct Foo3{T}
         ref::T
         ib::Int

         function Foo3(ref::T, ib::Int) where T
           return new{T}(ref, ib)
         end
       end

julia> Foo3(Foo1(1), 2)
Foo3{Foo1}(Foo1(1), 2)
  • Related