DataType to String

Hi All,
I’m writing a module with a function that converts an internal DataType into a string.
However, without importing/exporting the DataType, the module name is added to the string.

Example:

module A
    struct T1 end
    function to_string()
        s = T1()
        return string(typeof(s))
    end
end

julia> A.to_string()
"Main.A.T1"

julia> import .A.T1; A.to_string()
"T1"

In this example, is there a way for to_string() to return "T1" without importing or exporting T1 from module A?

julia> module Foo
       struct Bar end
       end
Main.Foo

julia> typeof(Foo.Bar())
Main.Foo.Bar

julia> string(nameof(typeof(Foo.Bar())))
"Bar"
1 Like
julia> string(nameof(Foo.Bar))
"Bar"

Is there any reason to construct an object, just to retrieve the name of its type, when one is explicitly using the type anyway?

1 Like

No. Depends on whether your function is supposed to operate on instances or types and OP’s to_string kinda sorta does the former…

Not sure. The code directly references T1, and it seems an unnecessary detour to put s = T1(); typeof(s), just to get back to T1. I guess @chiion needs to clarify.

Eh, feels like you’re overthinking this. @chiion will be able to figure out which one’s more appropriate for their use case.

Thanks, that’s exactly what I need.

I dunno. I have seen a lot of weird detours in code, so I like to point it out. Oh well.

1 Like