Variables
suggest changeVarious ways of defining variables:
// declaration of a single top-level variable
var topLevel int64 = 5
// grouping of multiple top-level declarations
var (
intVal int // value is initialized with zero-value
str string = "str" // assigning
// functions are first-class values so can be assigned to variables
// fn is variable of type func(a int) string
// it's uninitialized so is nil (zero-value for function variables)
fn func(a int) string
)
func f() {
// shorthand using local type inference
// type of `i` is int and is inferred from the value
// note: this is not allowed at top-level
i := 4
// grouping inside a function
var (
i2 int
s string
)
// _ is like a variable whose value is discarded. It's called blank identifier.
// Useful when we don't care about one of the values returned by a function
_, err := io.Copy(dst, src) // don't care how many bytes were written
// ...
fmt.Printf(`i: %d
i2: %d
s: %s
err: %v
`, i, i2, s, err)
}
i: 4
i2: 0
s:
err: <nil>
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
3 Variables
5 Strings
6 Pointers
7 Arrays
8 Slices
9 Maps
10 Structs
11 Interfaces
16 Functions
17 Methods
19 Defer
21 Concurrency
23 Mutex
24 Packages
28 Logging
31 JSON
32 XML
33 CSV
34 YAML
35 SQL
36 HTTP Client
37 HTTP Server
39 Reflection
40 Context
41 Package fmt
42 OS Signals
43 Testing
50 gob
51 Plugin
54 Console I/O
55 Cryptography
60 Contributors