Variables and programming languages go hand in hand, and Go is no different. In Go variables can be defined using the keyword var, the variable name and the variable type for example:
var name_of_player string
var player_score int
Or multiple variables can be defined using var () for example:
Variable names must start with a letter or an underscore _
Uninitialised variables (i.e variables with no values store in them) are give the value of zero.
Variables defined at the function level are not global, so thought should be given to where a variable is created (package or function) and where it will be altered or called on.
Note: Any defined variables must be used otherwise the Go compiler will generate an error when it tries to compile the Go program.
There are a few types that variables can be:
A string is made up of characters e.g. alphabetical characters.
A float is a decimal point number e.g. 45.89 or -2999.38
An integer is a whole number e.g. 9 or -9
A boolean value is TRUE or FALSE
To print the values of a variable:
fmt.Printf(“some text %v”, variable_name)
To print the type of a variable:
fmt.Printf(“some text %T”, variable_name)
As an alternative to declaring and then initialising them, variables can be initialised and declared at the same time using:
variable_name := variable_value
Passing Variable Values Between Packages / Functions
When passing variable values, Go actually copies the value to another memory address and passes the copied value. For example, if my variable of “name” contained “geektechstuff”, was set at the package level and this lived in memory address 0xAA when this variable is passed to function the value would stay the same but would be copied to another memory address (e.g. 0XBB) which would then be given to the function.
A variable’s memory address pointer can be checked or used by referencing the variable with an ampersand (&) in front of it. To dereference a variable’s memory pointer| replace the ampersand (&) with an asterisk (*).
Unlike variables constants, as the same suggest, are constant which means they cannot be changed once set. Constants cannot be declared using the := method. To create a constant the const keyword is used e.g.
const name string = “geektechstuff”
would create a constant called name, that is a string type and contains the string geektechstuff.
Note: Any defined constants must be used otherwise the Go compiler will generate an error when it tries to compile the Go program.