gpt4 book ai didi

Julia:如何在结构体中使用 @assert 宏? @with_kw vs Base.@kwdef

转载 作者:行者123 更新时间:2023-12-04 07:41:28 25 4
gpt4 key购买 nike

我想将 @assert 宏与结构一起使用。 来自包 Parameters 的 @with_kw 宏可以不使用构建在结构之上的显式方法,而 Base.@kwdef 需要显式方法。我理解正确吗?

# 1. outer constructor with "semi-colon" keyword + no keyword macro + @assert
struct myStruct1
a :: Float64
end
function myStruct1(;a::Float64=1.0)
@assert a > 0 "must be positive"
myStruct1(a)
end
myStruct1().a
## 1.0
myStruct1(a = -1.0).a
## ERROR: LoadError: AssertionError: must be positive

# 2.1. Base.@kwdef + no outer constructor + @assert
Base.@kwdef struct myStruct2
a :: Float64 = 1.0
@assert a > 0 "must be positive" # was hoping this would work
end
myStruct2().a
## ERROR: LoadError: UndefVarError: a not defined

# 2.2. Base.@kwdef + outer constructor + @assert
Base.@kwdef struct myStruct22
a :: Float64 = 1.0
end
function myStruct22(;a::Float64=1.0) # explicit method just to @assert
@assert a > 0 "must be positive"
myStruct22(a)
end
myStruct22().a
## 1.0
myStruct22(a = -1.0).a
## ERROR: LoadError: AssertionError: must be positive

# 2.3. @with_kw + outer constructor + @assert
using Parameters
@with_kw struct myStruct23
a :: Float64 = 1.0
@assert a > 0 "must be positive" # works without explicit method
end
myStruct23().a
## 1.0
myStruct23(a = -1.0).a
# ERROR: LoadError: AssertionError: must be positive

最佳答案

目前,Base.@kwdef不支持,因为正如您所说,它使用外部构造函数。您可以使用 @macroexpand 检查生成的代码宏:

julia> @macroexpand Base.@kwdef struct myStruct2
a :: Float64 = 1.0
@assert a > 0 "must be positive" # was hoping this would work
end
quote
#= util.jl:472 =#
begin
$(Expr(:meta, :doc))
struct myStruct2
#= REPL[3]:2 =#
a::Float64
#= REPL[3]:3 =#
if a > 0
nothing
else
Base.throw(Base.AssertionError("must be positive"))
end
end
end
#= util.jl:473 =#
myStruct2(; a = 1.0) = begin
#= util.jl:450 =#
myStruct2(a)
end
end
如您所见,结构定义中的断言代码而不是外部构造函数中的断言代码。

关于Julia:如何在结构体中使用 @assert 宏? @with_kw vs Base.@kwdef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67430487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com