Variables
Notes// archive From the original Code Walker docs. Kept for reference, so some versions and commands may be out of date.
All variables in Go are strongly typed meaning you have to declare the data type, for example:
var firstName string
var firstName string = "Richard"The shorthand version of the above is to let Go infer the type, and use the := syntax to declare and set the value of a variable:
firstName := "Richard"Type Conversion#
Be clear over being cleaver!
In Go you need to explicitly convert types, for example:
var price int = 48
var total float32
total = float32(price)Some examples:
main.gogo
package main
import "fmt"
func main() {
var a string = "foo"
fmt.Println(a)
var b int = 42
fmt.Println(b)
var c = true
fmt.Println(c)
d := 3.1415
fmt.Println(d)
var e int = int(d)
fmt.Println(e)
}Arithmetic#
Multi variables can be delard on one line:
a, b := 5, 6
c := a + b // addition
c := a - b // subtraction
c := a * b // multiplication
c := a / b // division
c := a % 3 // modulusComparisons#
a, b := 5, 6
c := a == b // false
c := a != b // true
c := a < b // false
c := a <= b // false
c := a > b // true
c := a >= b // trueExamples:
main.gogo
package main
import "fmt"
func main() {
a, b := 5, 2
fmt.Println(a + b)
fmt.Println(a - b)
fmt.Println(a * b)
fmt.Println(a / b)
fmt.Println(a % b)
fmt.Println(float32(a) / float32(b))
fmt.Println(a == b)
fmt.Println(a < b)
fmt.Println(a > b)
}