朱莉娅:如何为新数组类型编写用于repl的打印方法?

时间:2019-09-11 06:09:37

标签: julia

抱歉,代码有点长,但这是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

1 个答案:

答案 0 :(得分:3)

您想重载showBase中的Base.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