例如,我如何在自己的代码/包中添加标准包
@test
中定义的Test.jl
宏的方法。
执行以下操作似乎不起作用:
import Test: @test
macro test(ex::SomeArbitraryType, args...)
...
end
更具体地说,它不会在实际的
Test.@test
宏上注册额外的方法,
但只是定义了一个名为 @test
的新本地宏。
您可以添加新方法,但可以分派的类型有限:
Expr
、Symbol
、文字数字:
julia> using Test
julia> @test 1+1==2 # macro called with Expr type
Test Passed
julia> @which @test 1+1==2
var"@test"(__source__::LineNumberNode, __module__::Module, ex, kws...)
@ Test ~/.julia/dev/julia/usr/share/julia/stdlib/v1.12/Test/src/Test.jl:493
julia> function Test.var"@test"(__source__::LineNumberNode, __module__::Module, ex::Int, kws...)
println("new method for Int") # more specific signature
end
julia> @test 3 # macro called with Int type
new method for Int
如果
x isa SomeArbitraryType
在运行时,则 f(x) = @test x
立即调用 ::Symbol
的方法。该宏看到的是定义 f
所涉及的代码,而不是仅在调用 f
时才存在的值。