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.
Creating a multiline string in Go is actually incredibly easy. Simply use the backtick ( ` ) character when declaring or assigning your string value. str := `This is a multiline string. `
In Go language, string literals are created in two different ways: Using double quotes(“”): Here, the string literals are created using double-quotes(“”). This type of string support escape character as shown in the below table, but does not span multiple lines.
string in Golang is a set of all strings that contain 8-bit bytes. By default, strings in Golang are UTF-8 encoded. Variable of type string is enclosed between double-quotes. The type string variable's value is immutable. The value assigned to the type string variable can be empty but cannot be nil.
Go is a statically typed language, which means types of variables must be known at compile time, and you can't change their type at runtime.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With