📌  相关文章
📜  struct is not nil golang - Go 编程语言 - Go 编程语言(1)

📅  最后修改于: 2023-12-03 15:20:22.001000             🧑  作者: Mango

Struct is not nil in Golang

Struct is an important data type in Golang. It can be used to define a custom data structure with multiple fields. In Golang, structs are not nullable like pointers, but they can be nil.

Basics of Struct in Golang

A struct is a composite data type in Golang that groups together zero or more named values with different types. The named values are called fields, and the types may be any valid Golang type, including other structs.

Here's an example of a struct in Golang:

type Person struct {
    Name    string
    Age     int
    Address Address
}

type Address struct {
    Street  string
    City    string
    Country string
}
Nil Struct in Golang

In Golang, a struct can be nil if it is not initialized or assigned any value. However, it is important to note that a non-initialized struct is different from an empty struct. An empty struct is a struct with no fields.

Here's an example of a nil struct in Golang:

var person *Person
fmt.Printf("%v", person) // Output: <nil>
Checking for Nil Struct

When working with structs, it is important to check if a struct is nil or not before accessing its fields. This can be done using the reflect package. The IsNil() method can be used to check if a struct is nil or not.

Here's an example of checking for a nil struct in Golang:

var person *Person
if reflect.ValueOf(person).IsNil() {
    fmt.Println("person is nil")
} else {
    fmt.Println("person is not nil")
}
Conclusion

A struct in Golang can be nil if it is not initialized or assigned a value. It is important to check if a struct is nil or not before accessing its fields. Structs are not nullable like pointers, but they can be nil.