Macros 从基扩展“@show”

Macros 从基扩展“@show”,macros,julia,show,Macros,Julia,Show,如何将Base的@show宏扩展到我自己的类型? 例如: struct friendly string end Base.show(f::friendly) = f.string * " :)" p = friendly("people") 然后调用show(p)返回: "people :)" 但是@show p只是做了正常的事情(笔记本结果): 我尝试从基扩展宏: Base.@show(f::friendly) = f.string * " :)" 但这是一个错误: synt

如何将Base的
@show
宏扩展到我自己的类型?

例如:

struct friendly
    string
end

Base.show(f::friendly) = f.string * " :)"

p = friendly("people")
然后调用
show(p)
返回:

"people :)"
但是
@show p
只是做了正常的事情(笔记本结果):

我尝试从基扩展宏:

Base.@show(f::friendly) = f.string * " :)"
但这是一个错误:

syntax: invalid assignment location "begin
    Base.println("f::friendly = ", Base.repr(begin
    # show.jl, line 576
    #105#value = f::friendly
end))
    #105#value
end"

Stacktrace:
 [1] top-level scope at C:\Users\User\.julia\packages\IJulia\cwvsj\src\kernel.jl:52

@show
做了一件非常简单的事情:先打印表达式,然后打印表达式的值。如果您想要其他行为,您可能应该定义自己的宏。如果要控制如何在右侧打印值,则应扩展
Base.show
。扩展
Base.show
时,第一个参数是I/O缓冲区(例如
io::io
),并且您的方法写入该I/O缓冲区是非常重要的。这就是您的示例中缺少的内容。这项工作:

julia> struct Friendly
           x::String
       end

julia> Base.show(io::IO, f::Friendly) = print(io, f.x, " :)")

julia> f = Friendly("Hi")
Hi :)

julia> @show f;
f = Hi :)
请注意,更新的
Base.show
方法现在在Julia REPL中打印值时也会导致“漂亮打印”:

julia> f = Friendly("Hi")
Hi :)
julia> f = Friendly("Hi")
Hi :)