Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign a string type golang

Tags:

types

go

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.

like image 713
Rodrigo Avatar asked Feb 05 '16 18:02

Rodrigo


People also ask

How do I assign a string in Golang?

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. `

How do I declare a string variable in Golang?

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.

What is string data type in Golang?

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.

How do you change type in Golang?

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.


1 Answers

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.

like image 61
GerritS Avatar answered Oct 02 '22 12:10

GerritS