假设我有
@kwdef struct SomeParams
A::Float64
B::Float64
end
搬离
struct SomeParams
A::Float64
B::Float64
function SomeParams(C::Float64)
new(C^2, C + 0.5)
end
end
有没有一种鱼与熊掌兼得的好方法?
离开构造函数会产生关键字 args 的错误。
最佳答案
来自docs ,(强调我的)
This is a helper macro that automatically defines a keyword-based constructor for the type declared in the expression
typedef
, which must be astruct
ormutable struct
expression. The default argument is supplied by declaring fields of the formfield::T = default
orfield = default
. If no default is provided then the keyword argument becomes a required keyword argument in the resulting type constructor.Inner constructors can still be defined, but at least one should accept arguments in the same form as the default inner constructor (i.e. one positional argument per field) in order to function correctly with the keyword outer constructor.
因此,如果您想定义内部构造函数,则需要定义一个与 @kwdef
生成的外部构造函数兼容的版本。
如果您只是委托(delegate)给 @kwdef
构造函数,那么您可以编写一个外部构造函数并避免整个问题。
@kwdef struct SomeParams
A::Float64
B::Float64
end
SomeParams(C::Float64) = SomeParams(A=C^2, B=C + 0.5)
关于 Julia `@kwdef` -- 有 "extra constructors",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77011153/