This example shows that int type is convertible to string type. But my question is why?
package main
import (
"fmt"
"reflect"
)
func main() {
it := reflect.TypeOf(42)
st := reflect.TypeOf("hello")
fmt.Printf("%q is convertible to %q: %v\n",
it, st, it.ConvertibleTo(st))
// OUTPUT: "int" is convertible to "string": true
fmt.Printf("%q is convertible to %q: %v\n",
st, it, st.ConvertibleTo(it))
// OUTPUT: "string" is convertible to "int": false
}
Correct me if I'm wrong. But Shouldn't this be false
as well?
reflect.TypeOf(int(0)).ConvertibleTo(reflect.TypeOf("string"))
Why is “int” convertible to “string”?
Because the language spec1 says so:
Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer.
1: Conversions, section "Conversions to and from a string type"