From Golang Spec
A value x is assignable to a variable of type T ("x is assignable to
T") if:
- x's type is identical to T.
- x's type V and T have identical underlying types and at least one of V or T is not a defined type.
Variables of named type type User string
and unnamed type var user string
are absolutely different.
We can check that using reflection for showing the underlying type.
package main
import (
"fmt"
"reflect"
)
type User string
func main() {
var name User = "User"
var name2 string = "User"
//fmt.Print(name==name2) // mismatched types User and string
fmt.Println(reflect.TypeOf(name2))
fmt.Println(reflect.TypeOf(name))
}
So check the underlying type of a variable and then type cast the type to primitive one to compare the value.
package main
import (
"fmt"
)
type User string
func main() {
var u User
fmt.Print(SayHello(u))
}
func SayHello(u User) string {
change := string(u)
return "Hello " + change + "!"
}
Check on
Go Playground