作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将 @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/
我正在阅读一些看起来像这样的代码: @with_kw struct HyperParams batch_size::Int = 128 latent_dim::Int = 100
我想将 @assert 宏与结构一起使用。 来自包 Parameters 的 @with_kw 宏可以不使用构建在结构之上的显式方法,而 Base.@kwdef 需要显式方法。我理解正确吗? # 1.
我是一名优秀的程序员,十分优秀!