It was asked on #helpdesk earlier why one can do things like Symbol(Base) == :Base
, and if it's appropriate to use this in metaprogramming.
My answer was
Mason Protter said:
There's a method defined in
base/strings/basic.jl
which isSymbol(x...) = Symbol(string(x...))
Hence, this should work for any values:
string(xs...) Create a string from any values using the print function. string should usually not be defined directly. Instead, define a method print(io::IO, x::MyType). If string(x) for a certain type needs to be highly efficient, then it may make sense to add a method to string and define print(io::IO, x::MyType) = print(io, string(x)) to ensure the functions are consistent. Examples ≡≡≡≡≡≡≡≡≡≡ julia> string("a", 1, true) "a1true"
It's documented in the manual that
Symbol
does this:julia> @doc Symbol(x...) Symbol(x...) -> Symbol Create a Symbol by concatenating the string representations of the arguments together. Examples ≡≡≡≡≡≡≡≡≡≡ julia> Symbol("my", "name") :myname julia> Symbol("day", 4) :day4
so, yes it is appropriate, safe and robust to use this.
I think however this was an error in earlier versions of Julia for
nothing
, so maybe be careful with that.
Last updated: Nov 22 2024 at 04:41 UTC