容器的简单初始化

huangapple go评论75阅读模式
英文:

Easy initialisation of empty containers

问题

考虑以下代码。

  1. struct MyType
  2. data::Dict{Int, Float64}
  3. end
  4. MyType() = MyType(Dict{Int, Float64}())

必须重复data的类型有点笨拙,如果您有更多的变量和/或您的类型变得更复杂,问题会迅速变得难以处理。我可以避免这个吗?

英文:

Consider the following code.

  1. struct MyType
  2. data::Dict{Int, Float64}
  3. end
  4. MyType() = MyType(Dict{Int, Float64}())

Having to repeat the type of data is a bit clumsy, and the problem gets out of hand very quickly if you have more variables and/or your types get more complicated. Can I avoid this?

答案1

得分: 2

如果涉及的类型是具有默认构造函数(即具有无参数构造函数)的话,您可以使用以下的技巧。

  1. struct Default; end
  2. Base.convert(::Type{T}, ::Default) where T = T()
  3. struct MyType
  4. data::Dict{Int, Float64}
  5. end
  6. MyType() = MyType(Default())
英文:

If the type in question is default-constructible (i.e., it has a no-args constructor), you can use the following trick.

  1. struct Default; end
  2. Base.convert(::Type{T}, ::Default) where T = T()
  3. struct MyType
  4. data::Dict{Int, Float64}
  5. end
  6. MyType() = MyType(Default())

答案2

得分: 1

你可以这样做:

  1. Base.@kwdef struct MyType
  2. data::Dict{Int, Float64} = Dict{Int, Float64}()
  3. end

现在你可以直接写MyType()

  1. julia> MyType()
  2. MyType(Dict{Int64, Float64}())

我个人更喜欢使用Parameters包,它还影响了struct的显示方式:

  1. using Parameters
  2. @with_kw struct MyType
  3. data::Dict{Int, Float64} = Dict{Int, Float64}()
  4. end

现在在REPL中你会看到:

  1. julia> MyType()
  2. MyType
  3. data: Dict{Int64, Float64}
英文:

You can do:

  1. Base.@kwdef struct MyType
  2. data::Dict{Int, Float64} = Dict{Int, Float64}()
  3. end

And now you can just write MyType():

  1. julia> MyType()
  2. MyType(Dict{Int64, Float64}())

I personally more like the package Parameters which is additionally affecting how struct is displayed:

  1. using Parameters
  2. @with_kw struct MyType
  3. data::Dict{Int, Float64} = Dict{Int, Float64}()
  4. end

And now in REPL you can see:

  1. julia> MyType()
  2. MyType
  3. data: Dict{Int64, Float64}

答案3

得分: 1

以下是翻译好的部分:

以下这种巧妙的方法适用(截至Julia 1.8版本):

  1. MyType() = MyType((t() for t in MyType.types)...)

它不包括IntFloat64,所以它满足OP的条件。而且,它适用于具有许多字段和复杂结构的类型,因为它本质上是递归的。

英文:

The following hack-ish method works (as of Julia 1.8):

  1. MyType() = MyType((t() for t in MyType.types)...)

It doesn't include Int or Float64, so it passes OP conditions. And also, it generalizes to types with many fields, and complex ones because it is essentially recursive.

huangapple
  • 本文由 发表于 2023年2月8日 10:45:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75380934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定