Code-Memo

Variables

Go is statically typed. Types are checked at compile time. Variables can be declared in several ways.

Short variable declaration

Inside functions, use := when you want type inference.

x := 42          // int
name := "Go"     // string
ok := true       // bool
var

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
Multiple declaration
var i, j int = 1, 2
a, b := 0, "hello"
Constants

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
)
Variable naming


Data types

Numeric types
var n int = 10
var f float64 = 3.14
var c complex128 = 1 + 2i
String and runes
s := "Hello, δΈ–η•Œ"
for i, r := range s { // r is rune
	_ = i
	_ = r
}
Booleans
var active bool = true
Composite types
nums := []int{1, 2, 3}
user := struct{ Name string }{Name: "Ada"}
ages := map[string]int{"Ada": 36}
Zero values

Every type has a zero value: 0, 0.0, false, "", nil for pointers, slices, maps, channels, functions, and interfaces.

Type conversion

Go requires explicit conversion between numeric types and related types.

var x int32 = 10
y := int64(x)
Reading input (sketch)
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.