in

Golang – Variable Declaration, Assignment and Initialization

Formal Variable Declaration in Golang

In the Go language, variables are declared with the var keyword like so:

var [variable name] [Type] 

example: var name String

Formal Variable Assignment in Golang

To assign a variable that has been declared it follows a standard methodology:

var name String

name = “Brian”

Formal Variable Initialization in Golang

You can initialize a variable at the same time as declaring it:

var name String = “Brian”

Shorthand Variables in Golang

Golang also allows a shorthand variation of variable assignment/declaration. It should be noted however that this CAN ONLY BE DONE WITHIN A FUNCTION.  Any variables defined outside a function MUST be formally defined (as mentioned above.)

Shorthand works like this:

[variable name] := [value]

Example: name := “Brian”

Zero Value Assignment in Golang

Golang will also support variable declaration without assignment:

var a int

var b string 

var c boolean

In the above cases, Golang will assign a default value to each of the variables.

What do you think?

0 points
Upvote Downvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Written by Admin

I work for a Telecom company writing and testing software. My passion for writing code is expressed through this blog. It's my hope that it gives hope to any and all who are self-taught.

Go – Package Scope

Go – Unused Code and the Blank Identifer