Variables and Types
Variables are declared using the var
keyword or using the initial assignment operator :=
(only inside functions). The type of the variable comes last, and can be inferred if using the assignment operator. Variables can be at the package or function level. You can also declare constants with the const
keyword, but cannot use the :=
operator. Numeric constants can be used for high precision.
go
package main
import "fmt"
var c, python, java bool
func main() {
var i int
j := 3 // int inferred
const k = "Can't change this"
const Big = 1 << 100 // 1 shifted left 100 times
fmt.Println(i, c, python, java)
}
Types
The basic types in go are:
- bool
- string
- int, int8, int16, int32, int64
- uint, uint8, uint16, uint32, uint64, uintptr
- byte (alias for uint8)
- rune (alias for int32, represents a Unicode code point)
- float32, float64
- complex64, complex128
go
package main
import (
"fmt"
"math/cmplx"
)
var (
ToBe bool = false
MaxInt uint64 = 1<<64 - 1
z complex128 = cmplx.Sqrt(-5 + 12i)
)
func main() {
fmt.Printf("Type: %T Value: %v\n", ToBe, ToBe) // bool, false
fmt.Printf("Type: %T Value: %v\n", MaxInt, MaxInt) // uint64, 18446744073709551615
fmt.Printf("Type: %T Value: %v\n", z, z) // complex128, (2+3i)
}
Default Values (Zero values)
When not given an initial value, the below types default to:
- bool - false
- string - ""
- numeric - 0
Type Conversion
You can cast variables to different types by specifying the type in the below syntax.
go
var i int = 42
var f float64 = float64(i)
var u uint = uint(f)
Generic Types
Types can also be generic to work with multiple different types of arguments.
go
// Singly linked list
type Node[T any] struct {
next *Node[T]
val T
}