Rodrigo
Rodrigo

Reputation: 3278

assign a string type golang

I'm having a hard time assigned a string to a type string. So I have this type:

type Username string

I then have a function that returns a string

What I'm trying to do is set username to that returned string:

u := &Username{returnedString}

I also tried

var u Username
u = returnedString

But I always get an error.

Upvotes: 18

Views: 46290

Answers (3)

InkyDigits
InkyDigits

Reputation: 3228

You've made a user-defined type "Username". You cannot assign a value of one type to another type (in this case a string to Username) without converting. Incidentally you can assign a string literal to it.

var u Username
u = "test"

Will work.

var u Username
    var s string

    s = "test"
    u = s

Will give you the error:

cannot use s (type string) as type Username in assignment

You can convert from one type to another, so...:

var u Username
    var s string
    s = "test"
    u = Username(s)

...will also work. "u" will be of type Username with the value "test".

For the record these are not meant as idiomatic examples. I am simply trying to clearly illustrate what's going on with the types here.

Upvotes: 13

GerritS
GerritS

Reputation: 443

As others have pointed out, you'll need to do an explicit type conversion:

someString := funcThatReturnsString()
u := Username(someString)

I'd recommend reading this article on implicit type conversion. Specifically, Honnef references Go's specifications on assignability:

A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:

  • x's type V and T have identical underlying types and at least one of V or T is not a named type.

So in your example, the returnedString is already a "named type": it has type string. If you had instead done something like

var u Username
u = "some string"

you would have been ok, as the "some string" would be implicitly converted into type Username and both string and Username have the underlying type of string.

Upvotes: 20

Jacques Supcik
Jacques Supcik

Reputation: 659

Type casting in go is explained in the tutorial "A Tour of Go"

See here for an example using your types.

Upvotes: 1

Related Questions