We have seen how to print a basic set of characters (referred to as a string) to the console. We can work with a host of other values: integers, floats, booleans, etc. We can store these in “containers” in memory, variables. The name of the variable is how we can use the value stored in that container. We use var to declare one or more variables:
package main
import "fmt"
func main() {
var myName = "Joash"
var myAge = 13
fmt.Println(myName)
fmt.Println(myAge)
}
myName is a variable that will store a string because its initial value to set to “Joash”. myAge is an integer because its initial value is set to a number.
Go will infer the type of a variable if not specified. The inferred type will be based on the initial value given.
Shorthand notation for variable initialization
We can shorten the notation as in the following:
package main
import "fmt"
func main() {
yourName := "David"
yourAge := 24
fmt.Println(yourName)
fmt.Println(yourAge)
}
We can use := to set the variable on the left’s initial value to the value on the right. The inferred type of the variable will be based on whatever is placed on the right side of the :=.
Declaring a variable without giving it an initial value
When we do not want to set the value of a variable at time of declaration, we can simple declare it with the long notation. The variable will be zero-valued based on the type specified:
package main
import "fmt"
func main() {
var number int64
fmt.Println(number)
number = 43
fmt.Println(number)
var name string
fmt.Println(name)
var isCool bool
fmt.Println(isCool)
}
The initial value of the variable number will be zero ($0$). This is because the explicitly declared variable type (int64) has a zero value of $0$. The value of number is then set to $43$ and the variable printed again.
Strings will have an empty string ("") as their zero value. Booleans have a zero value of false.
Doing calculations
We can do a calculation on the right and store its value in the left side:
package main
import "fmt"
func main() {
n := 6.022e23 // Avogadro's number
e := 1.6e-19 // charge on an electron
x := n * e
fmt.Printf("There are %f Coulombs in a Faraday\n", x)
}
Here we store the result of multiplying Avogadro’s number (n) and the charge on an electron (e), into a new variable, x. The result is then printed to the user.
Constants
We can use constants in Golang to represent values that do not change. The notation resembles the long form for initializing variables, with const being used instead of var:
package main
import (
"fmt"
"math"
)
func main() {
const x = 100392
fmt.Println(x)
// using a context: convert to float64
fmt.Println(math.Sin(x))
// explicit conversion: convert to int32
fmt.Println(int32(x))
}
We can set the type of a numeric constant by using it in a specific context, or by an explicit conversion.