创建内部方法,其中“new”采用关键字参数

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

假设我有结构

struct MyStruct

    foo
    bar
    
    function MyStruct(foo::Number, bar::String)
         new(bar = "hello", foo = 2)
    end

end

然后我收到错误

ERROR: syntax: "new" does not accept keyword arguments around <path to file>

new
是否不能与kwargs一起使用,或者我错过了什么?在我的真实代码中,我有 20 个字段,因此我更喜欢在
new
中使用关键字参数,以确保它们确实为正确的字段设置了正确的值。

struct julia
1个回答
0
投票

有多种设置方法:

  • 使用
    Base.@kwdef
    Parameters.@with_kw
    ,这两个宏都会自动为您的结构定义关键字构造函数(带有默认参数)。如果您的结构有许多具有某些默认参数的字段,这非常有用。另请参阅 @kwdef 上的 Julia 文档
Base.@kwdef struct MyStruct
    foo = 2
    bar = "hello"
end
  • 自己定义一个关键字构造函数。如果您想要常规输入参数和关键字的组合,这尤其有用,例如:
struct MyStruct
    foo
    bar 
end

MyStruct(foo; bar="hello") = MyStruct(foo, bar)  # one could also write this as an inner constructor 

struct MyStruct
    foo
    bar 

    MyStruct(foo; bar="hello") = new(foo, bar)  # now as an inner constructor 
end
© www.soinside.com 2019 - 2024. All rights reserved.