julia 中 Struct 的默认值

问题描述 投票:0回答:1

这是我的代码

mutable struct Foo
    G::Graph
    S::Union{Tuple{Ring, Vector{QQMPolyRingElem}, Vector{QQMPolyRingElem}},
            Tuple{Ring, Vector{QQMPolyRingElem}, Vector{QQMPolyRingElem}, Vector{QQMPolyRingElem}}
            }


 # External constructor if S is given 
    # »for S (x,q,z) 
     function Foo(G::Graph, S::Tuple{QQMPolyRing, Vector{QQMPolyRingElem}, Vector{QQMPolyRingElem}, Vector{QQMPolyRingElem}})
        return new(G, S)
    end
   #.  » for S (x,q)
    function Foo(G::Graph, S::Tuple{QQMPolyRing, Vector{QQMPolyRingElem}, Vector{QQMPolyRingElem}})
        return new(G, S)
    end  

    # Inner constructor with default values for S (x,q,z)
    function Foo(G::Graph)
    
        S=@polynomial_ring(QQ, x[1:2], q[1:3], z[1:2])

        return new(G, S)
    end
 # Inner constructor with default values for S (x,q)
    function Foo(G::Graph)
        
        S=@polynomial_ring(QQ, x[1:2], q[1:3])


        return new(G, S)
    end

end

这段代码可以工作,但我觉得它可以用更简洁、更有效的方式编写。 我尝试了修改,但我得到了

UndefVarError: 
V
 not defined.

 mutable struct Foo {T, V <:Vector{T} where T <:QQMPolyRingElem}
G::Graph
S::Union{Tuple{Ring, V, V },
Tuple{Ring, V,V,V}
}

  function Foo(G::Graph, S::Tuple{Ring, V, V})
      return new(G, S)
  end

 # Inner constructor with default values for S
   function Foo(G::Graph)
      S=@polynomial_ring(QQ, x[1:2], q[1:3])
      return new{G, S)
    end
end 
struct constructor julia
1个回答
0
投票

https://docs.julialang.org/en/v1/base/base/#Base.@kwdef

可能有帮助。

另请参阅:Julia 中 @with_kw 和 Base.@kwdef 之间的区别?

例如:

Base.@kwdef mutable struct Foo {T, V <:Vector{T} where T <:QQMPolyRingElem}
    G::Graph
    S::Union{Tuple{Ring, V, V },Tuple{Ring, V,V,V}} = @polynomial_ring(QQ, x[1:2], q[1:3])
}
© www.soinside.com 2019 - 2024. All rights reserved.