How to Use Constructor Function for Struct in Go
In Go, a constructor function is a regular function that returns a pointer to a struct initialized with values. You define it by creating a function that returns
*StructName and sets the struct fields before returning it.Syntax
A constructor function in Go is a normal function that returns a pointer to a struct. It usually starts with New followed by the struct name. Inside, you create the struct, set its fields, and return its address.
func NewStructName(params) *StructName: Function signature returning a pointer.return &StructName{...}: Returns the address of the struct with fields set.
go
func NewPerson(name string, age int) *Person { return &Person{ Name: name, Age: age, } }
Example
This example shows how to define a Person struct and a constructor function NewPerson. It creates a new person and prints their details.
go
package main import "fmt" type Person struct { Name string Age int } func NewPerson(name string, age int) *Person { return &Person{ Name: name, Age: age, } } func main() { p := NewPerson("Alice", 30) fmt.Printf("Name: %s, Age: %d\n", p.Name, p.Age) }
Output
Name: Alice, Age: 30
Common Pitfalls
Common mistakes when using constructor functions in Go include:
- Returning the struct value instead of a pointer, which can cause unnecessary copying.
- Not initializing all fields, leading to zero values that may cause bugs.
- Using a constructor function name that does not start with
New, which is a Go convention for clarity.
go
package main import "fmt" type Person struct { Name string Age int } // Wrong: returns struct value, not pointer func NewPersonWrong(name string, age int) Person { return Person{ Name: name, Age: age, } } // Right: returns pointer func NewPersonRight(name string, age int) *Person { return &Person{ Name: name, Age: age, } } func main() { p1 := NewPersonWrong("Bob", 25) p2 := NewPersonRight("Carol", 28) fmt.Printf("p1: %+v\n", p1) fmt.Printf("p2: %+v\n", p2) }
Output
p1: {Name:Bob Age:25}
p2: &{Name:Carol Age:28}
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Constructor Function | A function that creates and returns a pointer to a struct | func NewX(...) *X { return &X{...} } |
| Return Pointer | Return a pointer to avoid copying and allow modification | return &StructName{...} |
| Naming Convention | Start constructor names with 'New' for clarity | NewPerson, NewCar |
| Initialize All Fields | Set all important fields to avoid zero values | return &Person{Name: name, Age: age} |
Key Takeaways
Use a constructor function to return a pointer to a struct with initialized fields.
Name constructor functions starting with 'New' followed by the struct name.
Always return a pointer to avoid copying and allow changes to the struct.
Initialize all necessary fields inside the constructor to prevent zero values.
Constructor functions are regular Go functions, not special language features.