Go is statically typed. Types are checked at compile time. Variables can be declared in several ways.
Inside functions, use := when you want type inference.
x := 42 // int
name := "Go" // string
ok := true // bool
Use var at package level or when you want a zero-valued variable without an initializer, or when the type is needed without an obvious right-hand side.
var count int // zero value: 0
var msg string // ""
var done bool // false
var p *User // nil
var m map[string]int // nil map β write with care
var i, j int = 1, 2
a, b := 0, "hello"
Use const for compile-time constants. iota generates incrementing values inside a const block.
const Pi = 3.14159
const (
Red = iota // 0
Green // 1
Blue // 2
)
camelCase (exported: MaxRetries, unexported: maxRetries).URL, HTTP, ID stay uppercase in exported names per Go style (ServeHTTP, userID vs UserID β see Effective Go for common conventions).int, int8, int16, int32, int64, uint, uint8 (byte), uint16, uint32, uint64, uintptrfloat32, float64complex64, complex128var n int = 10
var f float64 = 3.14
var c complex128 = 1 + 2i
string: immutable byte sequence (UTF-8 text by convention).rune: alias for int32; one Unicode code point.s := "Hello, δΈη"
for i, r := range s { // r is rune
_ = i
_ = r
}
var active bool = true
[4]int[]intmap[string]int*Tfunc(int) intchan intnums := []int{1, 2, 3}
user := struct{ Name string }{Name: "Ada"}
ages := map[string]int{"Ada": 36}
Every type has a zero value: 0, 0.0, false, "", nil for pointers, slices, maps, channels, functions, and interfaces.
Go requires explicit conversion between numeric types and related types.
var x int32 = 10
y := int64(x)
import "bufio"
import "os"
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
line := scanner.Text()
_ = line
}
Use fmt.Scan, fmt.Sscanf, or strconv for parsing numbers from strings.