zoukankan      html  css  js  c++  java
  • 结构体——内嵌,初始化内嵌结构体,内嵌结构体成员名字冲突

    1、内嵌

    结构体可以包含一个或多个匿名(或内嵌)字段,即这些字段没有显式的名字,只有字段的类型是必须的,此时类型也就是字段的名字。匿名字段本身可以是一个结构体类型,即结构体可以包含内嵌结构体。

    注意:在一个结构体中对于每一种数据类型只能有一个匿名字段

    1)内嵌的结构体可以直接访问其成员变量

    嵌入结构体的成员,可以通过外部结构体的实例直接访问。如果结构体有多层嵌入结构体,结构体实例访问任意一级的嵌入结构体成员时都只用给出字段名,而无须像传统结构体字段一样,通过一层层的结构体字段访问到最终的字段。例如,ins.a.b.c的访问可以简化为ins.c。

    2)内嵌结构体的字段名是它的类型名

    内嵌结构体字段仍然可以使用详细的字段进行一层层访问,内嵌结构体的字段名就是它的类型名。

    示例:

    package main
    import "fmt"
    type innerS struct {
    	in1 int
    	in2 int
    }
    type outerS struct {
    	b int
    	c float32
    	int // 匿名字段
    	innerS // 匿名字段
    }
    func main() {
    	outer := new(outerS)
    	outer.b = 6
    	outer.c = 7.5
    	outer.int = 60
    	outer.in1 = 5
    	outer.in2 = 10
    	fmt.Printf("outer.b is: %d
    ", outer.b)
    	fmt.Printf("outer.c is: %f
    ", outer.c)
    	fmt.Printf("outer.int is: %d
    ", outer.int)
    	fmt.Printf("outer.in1 is: %d
    ", outer.in1)
    	fmt.Printf("outer.in2 is: %d
    ", outer.innerS.in2)
    	outer2 := outerS{6, 7.5, 60, innerS{5, 10}}
    	fmt.Printf("outer2 is: %v", outer2)
    }
    

      

    2、初始化内嵌结构体

    1)

    结构体内嵌初始化时,将结构体内嵌的类型作为字段名像普通结构体一样进行初始化。

    示例:

    package main
    import "fmt"
    
    type Wheel struct {
    	Size int
    }
    
    type Engine struct {
    	Power int
    	Type  string
    }
    
    type Car struct {
    	Wheel
    	Engine
    }
    func main() {
    	c := Car{
    		Wheel: Wheel{
    			Size: 18,
    		},
    		Engine: Engine{
    			Type:  "1.4T",
    			Power: 143,
    		},
    	}
    	fmt.Printf("%+v
    ", c)
    }
    

      

    2)初始化内嵌匿名结构体

    有时考虑编写代码的便利性,会将结构体直接定义在嵌入的结构体中。也就是说,结构体的定义不会被外部引用到。在初始化这个被嵌入的结构体时,就需要再次声明结构才能赋予数据。

    示例:

    package main
    import "fmt"
    
    type Wheel struct {
    	Size int
    }
    
    type Car struct {
    	Wheel
    	Engine struct {
    		Power int
    		Type  string
    	}
    }
    func main() {
    	c := Car{
    		Wheel: Wheel{
    			Size: 18,
    		},
    		Engine: struct {
    			Power int
    			Type  string
    		}{
    			Type:  "1.4T",
    			Power: 143,
    		},
    	}
    	fmt.Printf("%+v
    ", c)
    }
    

      

     3、内嵌结构体成员名字冲突

    示例:

    package main
    import (
    	"fmt"
    )
    type A struct {
    	a int
    }
    type B struct {
    	a int
    }
    type C struct {
    	A
    	B
    }
    func main() {
    	c := &C{}
    	c.A.a = 1
    	c.B.a = 2
    	fmt.Println(c)
    }
    

      

  • 相关阅读:
    jquery下拉菜单打开的同时,同行右边的图标变化
    echarts引入及应用
    好用又美观的时间控件
    C#不支持此安全协议
    python re模块中的函数
    python中的收集参数
    python常用操作符
    python 字符串中常用的内置函数
    VS2012停止工作解决办法
    Jqurey图片放大镜插件
  • 原文地址:https://www.cnblogs.com/ACGame/p/11922901.html
Copyright © 2011-2022 走看看