How to initialise a struct in Go?
How to initialise a struct in Go?
In Go, there are several ways to initialize a struct, which is a typed collection of fields used to group data together. Here are the common methods:
Struct literals are the most straightforward way to create and initialize a struct. You can specify values for the fields in order or by naming them.
type Person struct {
Name string
Age int
}
// Using named fields (order does not matter)
p1 := Person{
Name: "Alice",
Age: 30,
}
// Using an ordered list (must be in the same order as struct definition)
p2 := Person{"Bob", 25}
new
KeywordThe new
keyword creates a pointer to a new struct instance, initializing all fields to their zero values.
p := new(Person)
// p is a pointer to a new Person struct with Name = "" and Age = 0
Go does not have constructors in the traditional sense, but you can create constructor-like functions that return an instance of the struct.
func NewPerson(name string, age int) *Person {
return &Person{
Name: name,
Age: age,
}
}
p := NewPerson("Charlie", 40)
For more complex initialization that might require default values or optional parameters, you can use a combination of exported fields and functional options.
type Person struct {
Name string
Age int
Address string
}
type PersonOption func(*Person)
func WithAddress(address string) PersonOption {
return func(p *Person) {
p.Address = address
}
}
func NewPerson(name string, age int, opts ...PersonOption)...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào