How to Pass Struct to Function in Go: Simple Guide
In Go, you can pass a struct to a function either by value or by pointer using
func myFunc(s MyStruct) or func myFunc(s *MyStruct). Passing by value copies the struct, while passing by pointer allows the function to modify the original struct.Syntax
To pass a struct to a function, define the function parameter with the struct type or a pointer to the struct. Passing by value copies the struct, and passing by pointer allows changes to affect the original.
func myFunc(s MyStruct): Pass by value (copy)func myFunc(s *MyStruct): Pass by pointer (reference)
go
package main import "fmt" type Person struct { Name string Age int } func greetByValue(p Person) { fmt.Println("Hello", p.Name) } func greetByPointer(p *Person) { fmt.Println("Hello", p.Name) }
Example
This example shows how to pass a struct by value and by pointer to functions. It also demonstrates how modifying the struct inside the function affects the original struct only when passed by pointer.
go
package main import "fmt" type Person struct { Name string Age int } func updateNameByValue(p Person) { p.Name = "Alice" } func updateNameByPointer(p *Person) { p.Name = "Bob" } func main() { person := Person{Name: "John", Age: 30} updateNameByValue(person) fmt.Println("After updateNameByValue:", person.Name) // John (unchanged) updateNameByPointer(&person) fmt.Println("After updateNameByPointer:", person.Name) // Bob (changed) }
Output
After updateNameByValue: John
After updateNameByPointer: Bob
Common Pitfalls
A common mistake is expecting changes inside a function to affect the original struct when passing by value. Since passing by value copies the struct, modifications inside the function do not change the original. To modify the original struct, always pass a pointer.
go
package main import "fmt" type Point struct { X, Y int } // Wrong: passing by value, changes won't persist func moveByValue(p Point) { p.X += 10 p.Y += 10 } // Correct: passing by pointer, changes persist func moveByPointer(p *Point) { p.X += 10 p.Y += 10 } func main() { pt := Point{X: 1, Y: 1} moveByValue(pt) fmt.Println("After moveByValue:", pt) // {1 1} moveByPointer(&pt) fmt.Println("After moveByPointer:", pt) // {11 11} }
Output
After moveByValue: {1 1}
After moveByPointer: {11 11}
Quick Reference
Remember these tips when passing structs to functions in Go:
- Use
func f(s MyStruct)to pass a copy. - Use
func f(s *MyStruct)to pass a pointer and allow modifications. - Passing large structs by pointer is more efficient.
- Use
&to get a pointer when calling the function.
Key Takeaways
Pass structs by value to send a copy and avoid modifying the original.
Pass structs by pointer to allow the function to modify the original struct.
Use & to pass the address of a struct when the function expects a pointer.
Passing large structs by pointer improves performance by avoiding copies.
Always be clear whether your function should modify the original struct or not.