The Division Surprise
Try the maths operators and meet integer division.
1package main
2
3import "fmt"
4
5func main() {
6 fmt.Println(7 + 3)
7 fmt.Println(7 * 3)
8 fmt.Println(7 / 2)
9 fmt.Println(7.0 / 2)
10}
$ go run main.go
10
21
3
3.5
Every line, explained
package main- Every Go file starts by saying which package it belongs to. package main means "this is a program you can run", and Go will look inside it for func main.
import "fmt"- import brings in a package from Go's standard library. "fmt" (short for format) is the one full of printing tools, like fmt.Println.
func main() {- func main() { ... } is where a Go program starts. When you run the program, Go finds func main inside package main and runs everything between its braces, top to bottom.
fmt.Println(7 + 3)- + adds two numbers together.
fmt.Println(7 * 3)- * means multiply: there is no × key on a keyboard, so programmers use the asterisk.
fmt.Println(7 / 2)- Surprise! This prints 3, not 3.5. Both 7 and 2 are whole numbers (ints), and dividing an int by an int in Go gives an int: the decimal part is simply chopped off.
fmt.Println(7.0 / 2)- Make either number a decimal and Go switches to decimal division: 3.5. Something to keep in mind whenever you divide!
}- This closing brace } ends func main.