lundi 5 juillet 2021

go: Why is an int reflect type convertible to a string reflect type?

I am surprised that reflect.TypeOf(1).ConvertibleTo(reflect.TypeOf("")) returns true. I am assuming that "convertible" means type conversion such as string(1), which is surly an compile error.

go version: go1.16.5 linux/amd64

Example:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    a := reflect.TypeOf(int(3))
    b := reflect.TypeOf(string("foo"))

    fmt.Println(a, b)
    // Output: int, string
    fmt.Println(a.ConvertibleTo(b))
    // Output: true Expected: false
}




Aucun commentaire:

Enregistrer un commentaire