I have a defined named type
type User string
and now I want to use a User
value as an actual string like so
func SayHello(u User) string {
return "Hello " + user + "!"
}
But I receive an error:
cannot use "Hello " + user + "!" (type User) as type string in return argument
How do I use a named type as its underlying type?
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
In this case you can use return "Hello " + string(user) + "!"
You could use fmt.Sprintf
without any additional conversion of your argument or concatenation of your parts of strings:
func SayHello(u User) string {
return fmt.Sprintf("Hello %s!", u)
}
Even if you change your type from string
to struct
you still would be able to use SayHello
if you'll implement method func (u *User) String() string
. However such approach would also work for regular string
conversion provided by goofle
.
Try it at https://play.golang.org/p/XnxeOucPZdE.
Two types are either identical or different.
A defined type is always different from any other type.
User is a defined type and consequently different from type string.
Since the underlying type of User is string, you can simply convert from one type to the other:
"Hello " + string(user) + "!"