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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
