~/Type Conversions in Golang Explained
Mar 15, 2021
Go or Golang requires explicit type conversions when changing a variable from one type to another. Go does not allow automatic or implicit type conversions, so you must use the syntax T(v) where T is the target type and v is the value.
Basic Example:
You cannot directly convert between unrelated types like string and int. To convert a string to int, use strconv.Atoi:
To convert an int to string:
Byte slice and string conversions are common. Convert string to byte slice:
And from byte slice to string:
If types are not explicitly convertible, Go will show a compile error. Always use the correct conversion or helper functions. For more, visit the Go spec on conversions.