Values
Go's basic types include true/false values, numbers, bytes, runes and strings.
Go checks that values match their types before a program runs. Its basic types include booleans, numbers, bytes and strings.
Boolean values are true or false. Go requires boolean conditions, so values such as 1 do not act as true.
package main
import "fmt"
func main() {
fmt.Println(true && false) // false
fmt.Println(true || false) // true
fmt.Println(!true) // false
}Go has signed integers, which can be negative, unsigned integers, which cannot, and two floating-point types for decimal numbers. int and uint use 32 or 64 bits, depending on the target computer.
package main
import "fmt"
func main() {
fmt.Println(1 + 2) // 3 (int)
fmt.Println(7.0 / 3.0) // 2.3333β¦ (float64)
fmt.Println(7 / 3) // 2 (integer division)
fmt.Println(7 % 3) // 1
var b byte = 255 // alias for uint8
fmt.Println(b) // 255
}Strings are read-only byte sequences, often encoded as UTF-8, which stores text using one or more bytes per character. A string can also hold arbitrary bytes. A rune holds one Unicode code point, a number identifying a character. A byte holds one value from 0 to 255.
package main
import "fmt"
func main() {
s := "Hello, δΈη"
fmt.Println(len(s)) // 13 - byte count, not character count
fmt.Println([]rune(s)) // slice of Unicode code points
for i, r := range s {
fmt.Printf("%d: %c\n", i, r)
}
// i is the byte offset; r is the rune at that offset
}In production
range reads one rune at a time. len and indexing count bytes, so s[3] is the fourth byte, not the fourth rune. Some displayed characters use several runes; use a text library when truncating by displayed characters.