Types
| Basic types | |
| Zero values table | |
| Conversions | |
| Inspect with reflect |
Basic types
Go programs are built from a small set of basic types: bool for logic, string for text, integers such as int, and floats such as float64.
Pick the type that matches the data: bool for flags, int for counts, float64 for measurements, and string for names and messages.
package main
import "fmt"
func main() {
var active bool = true
var title string = "course"
var count int = 7
var ratio float64 = 0.5
fmt.Println(active, title, count, ratio)
}
go run .
true course 7 0.5
Zero values table
Each type has a fixed zero value used before the first assignment.
Numbers start at 0, floats at 0.0, booleans at false, strings at the empty string, and composite types such as pointers and slices start at nil.
Knowing the table removes surprises: an unset counter reads as 0 and an unset flag reads as false.
Conversions
Go never converts types implicitly, so every conversion is written out with the target type or a helper from the strconv package.
Numeric conversions use the plain type name, while text conversions use Atoi, Itoa, and ParseFloat and report errors for bad input.
package main
import (
"fmt"
"strconv"
)
func main() {
n, err := strconv.Atoi("42")
text := strconv.Itoa(42)
asFloat := float64(n)
fmt.Println(n, text, asFloat, err)
}
go run .
42 42 42 <nil>
Inspect with reflect
When the type is unclear, the reflect package reports it at runtime with the TypeOf function.
The step-by-step examples live in the article
inspect variable types,
and the snippet below shows the core idea.
package main
import (
"fmt"
"reflect"
)
func main() {
age := 5
title := "course"
fmt.Println(reflect.TypeOf(age))
fmt.Println(reflect.TypeOf(title))
}
go run .
int
string
Next: Numbers
Article author: Arthur Isaev