I don’t really know much about parsing, so I’m just trying to reason my way through this, based on what seems intuitive (since no one properly knowledgeable has weighed in yet).
I believe you mean ‘convert’, not ‘cast’. They are different things, convert
calculates an equivalent value, creating new data in the process, while casting is like reinterpret
, and changes the interpretation without changing the underlying bits. Therefore it’s also really efficient.
You can actually convert a character to an integer:
jl> Int('A')
65
jl> Int('3')
51
Not what you expected? Characters numerals are not encoded as their corresponding integer values. Based on this, how do you turn “98765” into the number 98765? Strings are somewhat analogous to vectors, so what if you do
jl> Int.(collect("98765"))
5-element Vector{Int64}:
57
56
55
54
53
I don’t know what to do with this. Obviously, it’s much harder to parse strings to numbers than to convert, which should be straightforward and quick. ‘parsing strings’ means scanning them for meaning, and is a complicated process, comparatively. Just turning a string that you already know expresses a valid integer or float means iterating along it and calculating and combining it into some value that has meaning.
And this is complicated by various ways of expressing numbers in writing. How would you go about “converting” these strings to numbers:
"25.4e-3"
"0.0254"
"3654"
"0x00000e46" # this is actually the same as the line above
"3654 + 0im"
The mapping isn’t one-to-one, and you need to know how the encoding works. (Contrary to a type tag, like UInt8
which tells you how to interpret the data, a string doesn’t tell you if you are looking at an Int
, a Float32
, a Complex{Rational}
, or so on. You have to parse and interpret.)
Going the other way is also hard, and we don’t call it “converting a number to a string”, we call it “printing”. There is a string
function that turns 7
into “7”, but that is really printing, and String(7)
does not work.