是否可以声明对 Julia 中任何结构的一般引用?

roy*_*las 3 templates struct types reference julia

我想知道是否可以在结构内实现通用引用。代码是:

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)

Run Code Online (Sandbox Code Playgroud)

在上面的代码中,struct Foo2 中变量的类型ref直到运行时才确定。上面的代码不起作用,它显示:“LoadError("main.jl", 6, UndefVarError(:UNKNOWNTYPE))”。

pfi*_*seb 6

您基本上只是where UNKNOWNTYPE在构造函数定义中缺少 a 。我建议Foo2像这样使用外部构造函数

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)
Run Code Online (Sandbox Code Playgroud)

但内部构造函数也可以工作:

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)
Run Code Online (Sandbox Code Playgroud)