Golang中结构体的实现与应用探讨

Golang中结构体的实现与应用探讨 如果结构体如下所示:

type extra struct{
simple struct{
x int
y struct{
x int 				
}	
}
}

那么如何初始化结构体 extra。

5 回复

我的基本疑问是如何初始化匿名结构体

更多关于Golang中结构体的实现与应用探讨的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


我不确定是否完全理解了您的意思,能否请您提供更多代码来展示您想要实现的目标?

您可以使用playground或者使用markdown格式化代码后在这里发布。

通过不使其匿名或不断重复使用的方式。

由于我正在使用手机,无法提供示例。

附注:我坚决倾向于不使用匿名结构体,因为它们极大地增加了复杂性,却没有带来太多好处。

在Go语言中,初始化嵌套结构体extra需要逐层构建内部结构。以下是完整的示例代码:

package main

import "fmt"

type extra struct {
    simple struct {
        x int
        y struct {
            x int
        }
    }
}

func main() {
    // 方法1:声明后逐字段赋值
    var e1 extra
    e1.simple.x = 10
    e1.simple.y.x = 20
    
    // 方法2:使用复合字面量一次性初始化
    e2 := extra{
        simple: struct {
            x int
            y struct {
                x int
            }
        }{
            x: 30,
            y: struct {
                x int
            }{
                x: 40,
            },
        },
    }
    
    // 方法3:先定义内部结构类型,再初始化
    type innerY struct {
        x int
    }
    type innerSimple struct {
        x int
        y innerY
    }
    
    e3 := extra{
        simple: innerSimple{
            x: 50,
            y: innerY{
                x: 60,
            },
        },
    }
    
    fmt.Printf("e1: simple.x=%d, simple.y.x=%d\n", e1.simple.x, e1.simple.y.x)
    fmt.Printf("e2: simple.x=%d, simple.y.x=%d\n", e2.simple.x, e2.simple.y.x)
    fmt.Printf("e3: simple.x=%d, simple.y.x=%d\n", e3.simple.x, e3.simple.y.x)
}

输出结果:

e1: simple.x=10, simple.y.x=20
e2: simple.x=30, simple.y.x=40
e3: simple.x=50, simple.y.x=60

对于这种深度嵌套的匿名结构体,推荐使用方法3:先定义具名类型,这样代码更清晰易维护。方法2虽然可以一次性初始化,但语法较为冗长。

回到顶部