【问题标题】:Julia: how to write a printing method for repl for a new array type?Julia:如何为新的数组类型编写 repl 的打印方法?
【发布时间】:2019-09-11 06:09:37
【问题描述】:

抱歉,代码有点长,但它是 MWE。

说,我已经定义了一个模块,它定义了一个名为CmpVector 的新向量类型。我想覆盖打印到回购的文本。所以我已经覆盖、打印、显示和显示,但它仍然打印自己的东西。如何为新数组重载打印到 REPL??

module CmpVectors
    import Base:size,print,show,getindex, setindex!, display

    mutable struct CmpVector{T} <: AbstractVector{T}
        # compressed::Vector{UInt8}
        # vector_pointer::Ptr{T}
        inited::Bool
        # size::Tuple
    end

    size(pf::CmpVector{T}) where T = (1,)

    display(io::IO, pf::CmpVector{T}) where T = begin
        if pf.inited
            display(io, "NOO")
        else
            display(io, "Vector in compressed state")
        end
    end

    show(io::IO, pf::CmpVector{T}) where T = begin
        if pf.inited
            show(io, "NOO")
        else
            show(io, "Vector in compressed state")
        end
    end 

    print(io::IO, pf::CmpVector{T}) where T = begin
        if pf.inited
            show(io, "NOO")
        else
            print(io, "Vector in compressed state")
        end
    end

    getindex(pf::CmpVector{T}, i...) where T = zero(T)

end # module

我跑了这个


    using Revise
    using CmpVectors
    CmpVectors.CmpVector{Int}(true)

打印出来

1-element CmpVectors.CmpVector{Int64}:
 0

【问题讨论】:

    标签: julia


    【解决方案1】:

    您希望重载位于Base (Base.show) 中的show,而不是定义您自己的show。此外,您应该指定要重载的 MIME 类型。

    mutable struct MyType
        val::Symbol
    end
    
    function Base.show(io::IO, ::MIME"text/plain", mytype::MyType)
        println(io, "This is my type which contains $(mytype.val)")
    end
    
    
    MyType(:something)
    
    ## outputs
    This is my type which contains something
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-08
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-17
      • 2015-03-03
      • 1970-01-01
      相关资源
      最近更新 更多