Julia `@kwdef` -- 有 "extra constructors"

标签 julia

假设我有

@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 a struct or mutable struct expression. The default argument is supplied by declaring fields of the form field::T = default or field = 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/

相关文章:

julia - 如何使用 Julia 从 .CSV 文件数据中读取 DateTime 数据类型

Julia 短路

types - 哪些工具可用于检查/探测 Julia 中的类型

julia - 如何删除 Julia 中的特定行

julia - "Base"关键字在 Julia 中是什么意思?

package - Julia 中的 "Unsatisfiable requirements detected for the package"

Julia 内存

python - Julia 中使用 SymPy 进行多重替换

julia - 参数错误: No key column found Unstack Error?

python - 具有多个根的编程语言