Getting started
Basic types
Variables
Constants
Strings
Pointers
Arrays
Slices
Maps
Structs
Interfaces
Empty interface
if, switch, goto
for, while loops
range statement
Functions
Methods
Error handling
Defer
Panic and recover
Concurrency
Channels and select
Mutex
Packages
Files and I/O
Time and date
Command line arguments
Logging
Executing commands
Hex, base64 encoding
JSON
XML
CSV
YAML
SQL
HTTP Client
HTTP Server
Text and HTML templates
Reflection
Context
Package fmt
OS Signals
Testing
Calling C from GO with cgo
Profiling using go tool pprof
Cross compilation
Conditional compilation with build tags
Inlining functions
sync.Pool for better performance
gob
Plugin
HTTP server middleware
Protobuf in Go
Console I/O
Cryptography
Images (PNG, JPEG, BMP, TIFF, WEBP, VP8, GIF)
The Go Command
Testing code with CI services
Windows GUI programming
Contributors

Basics of pointers

suggest change

A pointer to a variable is the address of that variable in memory.

Unlike C++, Go doesn’t allow pointer arithmetic i.e. you can’t add or substract from pointers.

Zero value of a pointer is nil.

// We'll show how pointers work in contrast to values with
// 2 functions: `zeroval` and `zeroptr`. `zeroval` has an
// `int` parameter, so arguments will be passed to it by
// value. `zeroval` will get a copy of `ival` distinct
// from the one in the calling function.
func zeroval(ival int) {
	ival = 0
}

// `zeroptr` in contrast has an `*int` parameter, meaning
// that it takes an `int` pointer. The `*iptr` code in the
// function body then _dereferences_ the pointer from its
// memory address to the current value at that address.
// Assigning a value to a dereferenced pointer changes the
// value at the referenced address.
func zeroptr(iptr *int) {
	*iptr = 0
}

Once these functions are defined, you can do the following:

i := 1
fmt.Println("initial:", i)

zeroval(i)
fmt.Println("zeroval:", i)
// `i` is still equal to 1 because `zeroval` edited
// a "copy" of `i`, not the original.

// The `&i` syntax gives the memory address of `i`,
// i.e. a pointer to `i`. When calling `zeroptr`,
// it will edit the "original" `i`.
zeroptr(&i)
fmt.Println("zeroptr:", i)

// Pointers can be printed too.
fmt.Println("pointer:", &i)
initial: 1
zeroval: 1
zeroptr: 0
pointer: 0xc00007c010

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents