Golang / GoLang Basics Interview Questions
How do pointers work in Go and how are they safer than C pointers?
Go has pointers — variables that store the memory address of another variable — but removes the dangerous parts of C pointers. There is no pointer arithmetic, no manual memory management, and the garbage collector handles deallocation. A pointer to a local variable is safe to return from a function.
x := 42 p := &x // & gives the address of x; p is *int fmt.Println(*p) // 42 â * dereferences: gives the value at the address *p = 100 // modify x through the pointer fmt.Println(x) // 100 // new() â allocates a zeroed value and returns its pointer q := new(int) // *int pointing to 0 *q = 55 // nil pointer â the zero value for any pointer type var ptr *int fmt.Println(ptr) // // fmt.Println(*ptr) // PANIC: nil pointer dereference // Passing by pointer â allows a function to modify the caller's variable func increment(n *int) { *n++ } val := 10 increment(&val) fmt.Println(val) // 11 // SAFE: returning pointer to local â Go's escape analysis handles this type Point struct{ X, Y int } func newPoint(x, y int) *Point { p := Point{x, y} // may be allocated on heap by compiler return &p // safe in Go; would be dangling pointer in C! } // Auto-dereference on struct pointers â no -> operator needed pp := &Point{1, 2} pp.X = 10 // same as (*pp).X = 10
More Related questions...