十.Go结构struct

结构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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 01.{ 换行: Opening Brace Can't Be Placed on a Separate Lin...
    码农不器阅读 7,009评论 0 14
  • fmt格式化字符串 格式:%[旗标][宽度][.精度][arg索引]动词旗标有以下几种:+: 对于数值类型总是输出...
    皮皮v阅读 4,790评论 0 3
  • SwiftDay011.MySwiftimport UIKitprintln("Hello Swift!")var...
    smile丽语阅读 9,252评论 0 6
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,972评论 18 399
  • 结构struct -Go中的struct与C中的struct非常相似,并且Go没有class-使用type<Nam...
    战神汤姆阅读 3,122评论 0 1