Go supports conversion from rune
to byte
as it does for all pairs of numeric types. It would be a surprising special case if int32
to byte
conversion was not allowed.
But the underlying type for rune
is int32
(because Go uses UTF-8)
This misses an important detail: rune
is an alias for int32
. They are the same type.
It's true that the underlying type is rune
is int32
, but that's because rune
and int32
are the same type and the underlying type of a builtin type is the type itself.
The representation of Unicode code points as int32
values is unrelated to UTF-8 encoding.
the conversion therefore results in a loss of information
Yes, conversions between numeric types can result in loss of information. This is one reason why conversions in Go must be explicit.
Note that the statement var b byte = '©'
does not do any conversions. The expression '@'
is an untyped constant.
The compiler reports an error if the assignment of an untyped constant results in a loss of information. For example, the statement var b byte = '世'
causes a compilation error.
All UTF-8 encoding functionality in the language is related to the string
type. The UTF-8 aware conversions are all to or from the string
type. The []byte(numericType)
conversion could be supported, but that would bring UTF-8 encoding outside of the string
type.
The Go authors regret including the string(numericType)
conversion because it's not very useful in practice and the conversion is not what some people expect. A library function is a better place for the functionality.