假设我有结构
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
中使用关键字参数,以确保它们确实为正确的字段设置了正确的值。
有多种设置方法:
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