How to convert any type to String in Julia

Using Julia, I would like to reliably convert any type to type String. There seem to be two ways to do the conversion to v0.5, either a function Stringor a constructor String. The problem is that you need to choose the right option depending on the type of input.

For example, typeof(string(1))evaluated as String, but String(1)throws an error. On the other hand, typeof(string(SubString{String}("a")))evaluated as Substring{String}which is not a subtype String. Instead, we must do String(SubString{String}("a")).

So it seems like the only reliable way to convert any input xto type Stringthrough a construct:

String(string(x))

which feels a little bulky.

Am I missing something?

+6
source share
1 answer

You rarely need to explicitly convert to String. Note that even if your type definitions have fields String, or if your arrays have a specific element type String, you can still rely on implicit conversion.

For example, here are some examples of implicit conversions:

type TestType
    field::String
end

obj = TestType(split("x y")[1])  # construct TestType with a SubString
obj.field  # the String "x"

obj.field = SubString("Hello", 1, 3)  # assign a SubString
obj.field  # the String "Hel"
+3
source

Source: https://habr.com/ru/post/1014543/


All Articles