Declaring and assigning variables in Go

There's multiple ways of declaring a variable in Go.

You can do this:

var VarName TypeName

So, for example,

var s string

declares a variable s with a type of string. If I want to declare multiple variables, I can do this:

var (
s string
x int

which declares s as string, and x as an integer, or declare it one at a time:

var s string
var x int

I can also declare a variable and assign it at the same time.

s := "Hello world"

declares s as a variable of type string and assigns it the value of "Hello world".

If s is already declared, then assigning is as simple as:

s = "Hello world"

Similarly, if I want to declare and assign s to the value of a function returning a string:

s := FuncReturningString()


s = FuncReturningString() if s is declared as a string previously.


Published Mon, 14 May 2018 @ 2:10 PM by chuacw
Related articles: ,