使用 new 初始化嵌套结构

Initialize nested struct using new

这是我的 Go 代码。也可在 Go Playground

package main

import "fmt"

type App struct {
    OneHandler *OneHandler
    TwoHandler *TwoHandler
}
type OneHandler struct {
}
type TwoHandler struct {
    NestedTwoHandler *NestedTwoHandler
}
type NestedTwoHandler struct {
    NestedNestedTwoHandler *NestedNestedTwoHandler
}
type NestedNestedTwoHandler struct {
}

func main() {
    app := &App{
        OneHandler: new(OneHandler),
        TwoHandler: new(TwoHandler),
    }

    fmt.Println(*app)
    fmt.Println(*app.OneHandler)
    fmt.Println(*app.TwoHandler)
}

它的输出是

{0x19583c 0x1040c128}
{}
{<nil>}

为什么是NestedTwoHandlernil?我期待它是 {some_pointer_location}NestedNestedTwoHandler{}。如何使用 new 创建一个空的深层嵌套结构?

new(TwoHandler) 正在创建结构 TwoHandler 的新实例。它的所有字段都将为零值。对于指针类型,这是 nil,因此除非您指定它,否则这就是 NestedTwoHandler

new 只会清零内存,所以如果你想初始化任何东西,你需要使用其他东西,比如 composite literal:

    TwoHandler: &TwoHandler{new(NestedTwoHandler)},

这将创建一个指向 TwoHandler 结构的指针,其中唯一的字段设置为新的 NestedTwoHandler。请注意,TwoHandler.NesterTwoHandler.NestedNestedTwoHandler 将是 nil,因为我们再次使用 new,因此它仍然是零值。

您可以继续使用文字初始化字段:

    TwoHandler: &TwoHandler{&NestedTwoHandler{new(NestedNestedTwoHandler)}}

您可以阅读有关 allocating with new 的更多详细信息。