Go Data Types
A data type is the kind of value a variable holds. Each type stores its own kind of value, like whole numbers or text.
Types with %T
Printf with %T prints the type of each value. The four values show int, string, float64, and bool.
package main
import "fmt"
func main() {
age := 27
name := "Hana"
price := 12.5
var member bool
fmt.Printf("%T\n", age)
fmt.Printf("%T\n", name)
fmt.Printf("%T\n", price)
fmt.Printf("%T\n", member)
}Two float sizes
The two variables hold the same value with two types. %T tells float32 from float64 in the output.
package main
import "fmt"
func main() {
var small float32 = 2.5
var large float64 = 2.5
fmt.Printf("%T\n", small)
fmt.Printf("%T\n", large)
}A rune prints its code
A rune literal sits in single quotes. Printing the rune shows its number code, and the letter A has code 65.
package main
import "fmt"
func main() {
letter := 'A'
fmt.Println(letter)
}Example
package main
import "fmt"
func main() {
name := "Bo"
score := 88
var big int64 = 1234567890123
var rate float32 = 1.5
fmt.Printf("score %d is %T\n", score, score)
fmt.Printf("big %d is %T\n", big, big)
fmt.Printf("rate %v is %T\n", rate, rate)
fmt.Printf("name %s is %T\n", name, name)
}Key points
- Use %T with Printf to print the type of a value.
- The int type stores whole numbers.
- The string type stores text.
- The float64 type stores decimal numbers.
- The bool type stores true or false.
- A byte stores a small whole number from 0 to 255.
- A rune stores a number code for one character.
In this example, each line prints a value beside its type. score is an int, big is an int64, and rate is a float32. The last line shows that name holds a string.
Note
A plain int fits the machine that runs the program. The size of int64 stays the same on every machine.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Go data types
| Type | Stores | Example |
|---|---|---|
| string | Text | "Hello" |
| int | Whole numbers | 42 |
| int64 | Large whole numbers | 9000000000 |
| uint | Whole numbers from 0 up | 7 |
| float32 | Decimal numbers with less precision | 5.5 |
| float64 | Decimal numbers with more precision | 19.99 |
| bool | True or false values | true |
| byte | Small whole numbers from 0 to 255 | 200 |
| rune | A number code for one character | 'A' |
Exercise
What does %T print for the value 12.5?