Go Notes: Variables
Updated: 8th of February 2021
Published: 19th of November 2019
There are a number of methods to define variables in Go.
// Initialise variable with its zero value // explicitly defining the variables type var stuff string // Assign a value to "stuff" variable stuff = "stuff" // Initialise variable and assign a value var stuff string = "stuff" // Shortcut method to initialise variable and assign a value // The type will be inferred from the value // This method can only be used inside a function stuff := "stuff" // Declare multiple variables on a single line var stuff, things string = "stuff", "things" // Alternate method to declare multiple variables var ( stuff = "stuff" things = "things" ) // Constants are variables were the value cannot be changed const stuff string = "stuff"
- Variable names must begin with a letter or a number
- When a variable is declared but not yet assigned it has a default value for its type
- A variable that is declared must be used
- Constants can only be assigned at the package level