18

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.

3
  • Username is a string, not a struct, so you can't do u :=&Username{returnedString}. Is there a reason you can't do var u string? Commented Feb 5, 2016 at 18:26
  • Can you give more detail about the error? Commented Feb 5, 2016 at 18:34
  • @william.taylor.09 Username is not a string but a custom type built on a underlying type string. Commented Feb 5, 2016 at 19:36

3 Answers 3

20

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.

Sign up to request clarification or add additional context in comments.

Comments

13

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.

Comments

1

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

See here for an example using your types.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.