On todays’s livestream, we’ll be Pair Programming on a real project. I hope to see you there!
Conversions
A conversion changes the type of an expression to the type specified by the conversion. A conversion may appear literally in the source, or it may be implied by the context in which an expression appears.
An explicit conversion is an expression of the form
T(x)
whereT
is a type andx
is an expression that can be converted to typeT
.Conversion = Type "(" Expression [ "," ] ")" .
This seems like a good time to address a common confusion of terminology among beginning Go programmers:
As we see above, Go supports type conversion. But you may see this incorrectly referred to as type casting. What’s the difference? Why does it matter?
While there’s some ambiguity around these terms (as there are with most English language terms), generally speaking, type casting presents the same underlying memory through a different type.
As a simple example, given the in-memory bytes 1001000
and 1101001
, this could represent the string Hi
, the 16-bit integer 18537
, or two 8-bit integer values, 72
and 105
. And in a language like C, you can change the interpretation of the same memory locations through type casting, without allocating any new memory.
Except through clever use of the unsafe
package, Go does not support this sense of type casting. Rather, it does type conversion.
So that’s the difference. (Why) does it matter?
Well, it often doesn’t matter if someone uses the “wrong” term to describe converting from a 16-bit integer to a 32-bit integer, for example. What does matter is a recognition that when you convert types in Go, you allocate new memory. If you’ve come from a language like C, where type casting uses existing memory, this can potentially have a big impact on the performance and memory usage of your program.
On the other hand, if you didn’t know the difference between type casting and type conversion before reading this, or if you’re still confused, then it probably does not matter. At least not in a practical sense.
It still might be nice to use the “technically correct” term, though. You decide. 😊
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)