Câu hỏi phỏng vấn Golang
Câu hỏi

How to initialise a struct in Go?

Câu trả lời

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:

Using Struct Literals

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.

go Copy
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}

Using the new Keyword

The new keyword creates a pointer to a new struct instance, initializing all fields to their zero values.

go Copy
p := new(Person)
// p is a pointer to a new Person struct with Name = "" and Age = 0

Using Constructor Functions

Go does not have constructors in the traditional sense, but you can create constructor-like functions that return an instance of the struct.

go Copy
func NewPerson(name string, age int) *Person {
    return &Person{
        Name: name,
        Age:  age,
    }
}

p := NewPerson("Charlie", 40)

Using Field Defaults and Functional Options

For more complex initialization that might require default values or optional parameters, you can use a combination of exported fields and functional options.

go Copy
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

middle

Gợi ý câu hỏi phỏng vấn

senior

How does Go compile so quickly?

middle

What would you do if you need a hash displayed in a fixed order?

entry

Is Go a new language, framework or library?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào