Pointers Flashcards
What is a pointer in Go?
A pointer stores the memory address of another variable and holds a number representing a memory location. Its zero value is nil
.
What are the &
and *
operators used for in Go pointers?
-
&
: Address operator, gives the memory address of a value. -
*
: Indirection operator, dereferences a pointer to get the value at the address.
What is the syntax for defining a pointer type in Go?
A pointer type is written with *
before the type name, e.g., *int
for a pointer to an integer.
What does the built-in new
function do in Go?
It creates a pointer to a zero-initialized variable of a given type. However, it is rarely used in practice.
Why can’t you directly assign a string literal to a pointer field in a struct?
Go does not automatically take the address of a string literal. Instead, a helper function like makePointer
must be used.
How does Go handle function arguments—by value or by reference?
Go is call-by-value. Non-pointer types are copied, while pointer types pass a copy of the pointer, allowing modification of the original data.
Why are pointers considered a last resort in Go?
They increase the workload of the garbage collector, making memory management less efficient.
What is the difference between a zero value and no value in Go pointers?
A nil
pointer represents an uninitialized variable, whereas a zero value indicates an assigned but empty state.
Why are maps in Go inherently mutable when passed to functions?
Because passing a map to a function passes a copy of the internal pointer, allowing modifications to reflect in the original.
How do slices behave when passed to functions?
Modifying elements in a slice affects the original, but appending creates a new slice if capacity is exceeded.
What is an idiomatic way to use slices in Go?
Avoid unnecessary allocations and use slices as buffers to minimize garbage collection.
What fields does a slice struct contain in Go?
A slice has three fields:
- A pointer to the memory block
- A length
- A capacity
How can you reduce the workload on Go’s garbage collector?
Use pointers sparingly and avoid unnecessary memory allocations.