美文网首页
十.Go结构struct

十.Go结构struct

作者: kaxi4it | 来源:发表于2017-06-21 00:15 被阅读0次

    结构struct

    • Go中的struct与C中的struct相似,并且go没有class
    • 使用type 结构名称 struct{}定义结构,名称遵循可见性规则
    • 支持指向自身的指针类型成员
    • 支持匿名结构,可用作成员或定义成员变量
    • 可以使用字面值对结构进行初始化
    • 允许直接通过指针来读写结构成员
    • 相同类型的成员可进行直接拷贝赋值
    • 支持==和!=比较运算符,不支持< >
    • 支持匿名字段,本质上是定义ile以某个类型名为名称的字段
    • 嵌入结构作为匿名字段看起来像继承,但不是继承
    • 可以使用匿名字段指针
    package main
    import (
        "fmt"
    )
    type animal struct {
        Name string
        Age  int
    }
    type cat struct {
        animal
        Legs  int
        Sound string
    }
    type dog struct {
        animal
        Age int
    }
    type unknow struct {
        Name    string
        Details struct {
            Age, Country string
        }
    }
    func main() {
        c1 := &cat{Legs: 4, Sound: "喵", animal: animal{Name: "Tom", Age: 2}}
        fmt.Println(c1)
        modifyCat(c1)
        fmt.Println(c1)
        c2 := &struct {
            Name string
            Age  int
        }{
            Name: "王大锤",
            Age:  22,
        }
        fmt.Println(c2)
        u1 := &unknow{Name: "外星人"}
        u1.Details.Age = "111"
        u1.Details.Country = "火星"
        fmt.Println(u1)
        d1 := &dog{}
        d1.animal.Name = "狗狗"
        d1.Age = 6
        d1.animal.Age = 10
        fmt.Println(d1)
        d2 := &dog{animal: animal{Name: "狗狗Tom", Age: 12}, Age: 9}
        fmt.Println(d2)
    }
    func modifyCat(mCat *cat) {
        mCat.Name = "Jerry"
        mCat.Age = 1
        mCat.Legs = 5
        mCat.Sound = "喵喵"
    }
    

    直通车

    一.Go开发工具及命令
    二.Go编程基础知识
    三.Go的类型与变量
    四.Go常量与运算符
    五.Go控制语句
    六.Go数组
    七.Go切片slice
    八.Go哈希字典map
    九.Go函数func
    十.Go结构struct

    相关文章

      网友评论

          本文标题:十.Go结构struct

          本文链接:https://www.haomeiwen.com/subject/icjaqxtx.html