Data Types in Go
Go is statically typed with a simple type system.
Basic Types:
- bool: true or false
- string: UTF-8 encoded text
- int, int8, int16, int32, int64
- uint, uint8, uint16, uint32, uint64
- float32, float64
- complex64, complex128
- byte (alias for uint8)
- rune (alias for int32, represents Unicode)
Variable Declaration:
- var name type = value
- var name = value (type inferred)
- name := value (short declaration, inside functions only)
Zero Values: Uninitialized variables have zero values:
- Numbers: 0
- Booleans: false
- Strings: ""
- Pointers/slices/maps: nil
Code Examples
Go Data Typesgo
package main
import "fmt"
func main() {
// Variable declaration styles
var explicit string = "Hello"
var inferred = "World"
short := "Go"
fmt.Println(explicit, inferred, short)
// Numeric types
var i int = 42
var f float64 = 3.14
var b bool = true
fmt.Printf("int: %d, float: %.2f, bool: %t\n", i, f, b)
// Zero values
var (
defaultInt int
defaultFloat float64
defaultString string
defaultBool bool
)
fmt.Printf("Zero values: %d, %f, %q, %t\n",
defaultInt, defaultFloat, defaultString, defaultBool)
// Constants
const Pi = 3.14159
const (
StatusOK = 200
StatusError = 500
)
fmt.Println("Pi:", Pi)
// Type conversion (explicit only)
var x int = 42
var y float64 = float64(x)
var z int = int(y)
fmt.Printf("Conversions: %d -> %.2f -> %d\n", x, y, z)
// Strings and runes
s := "Hello, 世界"
fmt.Printf("String: %s, Length: %d, Runes: %d\n",
s, len(s), len([]rune(s)))
}Go requires explicit type conversion - there's no implicit casting. Zero values make uninitialized variables safe.
Quick Quiz
1. What is the zero value for a string in Go?
Was this lesson helpful?