How to Return a Pointer from a Function in Go

You return a pointer by declaring the function's return type with an asterisk (e.g., `*MyType`) and returning the address of a variable using the `&` operator.

You return a pointer by declaring the function's return type with an asterisk (e.g., *MyType) and returning the address of a variable using the & operator. This allows the caller to modify the original data or avoid copying large structs, but you must ensure the variable you are pointing to remains in scope after the function returns.

Here is a practical example returning a pointer to a struct defined within the function. Since the variable p is local to createPerson, returning &p is safe because Go's garbage collector manages the memory; the pointer remains valid as long as the caller holds a reference to it.

package main

import "fmt"

type Person struct {
	Name string
	Age  int
}

// Returns a pointer to a Person struct
func createPerson(name string, age int) *Person {
	p := Person{Name: name, Age: age}
	return &p // Return the address of p
}

func main() {
	// Get the pointer
	person := createPerson("Alice", 30)

	// Modify the original struct via the pointer
	person.Age = 31
	person.Name = "Alice Smith"

	fmt.Printf("Name: %s, Age: %d\n", person.Name, person.Age)
	// Output: Name: Alice Smith, Age: 31
}

If you need to return a pointer to a variable defined outside the function, simply pass the address or the variable itself and return its address. Be careful not to return a pointer to a temporary value that will be discarded immediately, though this is rare in Go unless you are manually managing memory with unsafe or returning a pointer to a local variable in a specific closure context where the variable goes out of scope unexpectedly.

func updateAge(p *Person, newAge int) {
	p.Age = newAge
}

func main() {
	p := &Person{Name: "Bob", Age: 25}
	updateAge(p, 26)
	fmt.Println(p.Age) // Output: 26
}

Use pointers when you need to modify the caller's data, pass large structs efficiently, or represent optional values (where nil indicates absence). If you only need to read the data and the struct is small, returning the value directly is often clearer and safer.