在 Julia 中抑制自定义结构的打印

Suppress Printing for Custom Structures in Julia

我的结构最终有很多循环引用。它类似于:

mutable struct Friend
a                    :: Int64
b                    :: Float64
your_best_friend     :: Union{Nothing, Friend}
you_are_best_friend  :: Union{Nothing, Friend}
Friend() = new()
end

任何两个互为至交的人在打印时都会引起循环引用。 Julia 处理这些循环引用,因此打印不会永远持续下去,但我更愿意在创建结构 Friend 的变量时完全不打印。我知道 supressor.jl 是一回事,但我想知道 Base Julia 是否有固有的解决方案。基本上,是否有结构选项,以便在不使用额外包的情况下分配时不打印对象?如果不是,下一个最好的事情是什么?我不是 CS 专家,所以我不确定打印需要什么样的计算时间,但我想尽可能避免它(而且我不确定 supressor.jl 是否会删除打印时间或者是否打印仍然需要额外的时间,但不会显示)。这对我来说似乎很简单,但我在文档中找不到解决方案。抱歉,如果很明显,请提前致谢!

-J

您需要重载 Base.show 以更改 REPL 显示对象的方式:

julia> mutable struct Friend
   a                    :: Int64
   b                    :: Float64
   your_best_friend     :: Union{Nothing, Friend}
   you_are_best_friend  :: Union{Nothing, Friend}
   Friend() = new()
   end

julia> Friend()
Friend(0, 0.0, #undef, #undef)

julia> import Base.show

julia> show(io::IO, f::Friend) = show(io, "Friend $(f.a)")
show (generic function with 223 methods)

julia> d = Friend()
"Friend 0"

请注意,如果您还想更改 REPL 命令行之外的打印方式,您可能还需要通过 import Base.print

重载打印