Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use string defined type value as string

Tags:

typedef

go

I have defined a type in the following way

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 saying

cannot use "Hello " + user + "!" (type User) as type string in return argument

How do I use a typedef'd type as its underlying type?


1 Answers

Go does not have typedefs.

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) + "!"
like image 128
Peter Avatar answered Oct 30 '25 11:10

Peter