容器的简单初始化

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

Easy initialisation of empty containers

问题

考虑以下代码。

struct MyType
    data::Dict{Int, Float64}
end

MyType() = MyType(Dict{Int, Float64}())

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

英文:

Consider the following code.

struct MyType
    data::Dict{Int, Float64}
end

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

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

struct Default; end
Base.convert(::Type{T}, ::Default) where T = T()

struct MyType
    data::Dict{Int, Float64}
end

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.

struct Default; end
Base.convert(::Type{T}, ::Default) where T = T()

struct MyType
    data::Dict{Int, Float64}
end

MyType() = MyType(Default())

答案2

得分: 1

你可以这样做:

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

现在你可以直接写MyType()

julia> MyType()
MyType(Dict{Int64, Float64}())

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

using Parameters 
@with_kw struct MyType
    data::Dict{Int, Float64} = Dict{Int, Float64}()
end

现在在REPL中你会看到:

julia> MyType()
MyType
  data: Dict{Int64, Float64}
英文:

You can do:

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

And now you can just write MyType():

julia> MyType()
MyType(Dict{Int64, Float64}())

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

using Parameters 
@with_kw struct MyType
    data::Dict{Int, Float64} = Dict{Int, Float64}()
end

And now in REPL you can see:

julia> MyType()
MyType
  data: Dict{Int64, Float64}

答案3

得分: 1

以下是翻译好的部分:

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

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

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

英文:

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

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:

确定