zoukankan      html  css  js  c++  java
  • go 结构体与方法

    go 结构体与方法

     

    go 结构体相当于 python 中类的概念,结构体用来定义复杂的数据结构,存储很多相同的字段属性

    结构体的定义

    1、结构体的定义以及简单实用

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        type Student struct { //定义结构体
            name string
            age  int
        }
        s1 := new(Student) // 定义指向结构体的指针
        s1.name = "xiaomu"
        s1.age = 10
        fmt.Printf("name:%s
    age:%d
    ", s1.name, s1.age)
    }
    
    

    结构体定义的三种方式,例如上面的 Student 类型,有如下方式定义

    ①var s1 Student 在内存中直接定义一个结构体变量
    ②s1 := new(Student) 在内存中定义一个指向结构体的指针
    ③s1 := &Student{} 同上

    通过以下方式获取存储的值

    ①s1.name
    ②s1.name或者(*s1).name
    ③同上

    2、struct 中的“构造函数”,称之为工厂模式,见代码

    package main
    
    import (
        "fmt"
    )
    
    type Student struct { //声明结构体
        Name string
        Age  int
    }
    
    func NewStudent(name string, age int) *Student { // 返回值指向 Student 结构体的指针
        return &Student{
            Name: name,
            Age:  age,
        }
    }
    
    func main() {
        s1 := NewStudent("xiaomu", 123) // 声明并且赋值指向Student结构体的指针
        fmt.Printf("name: %s
    age: %d", s1.Name, s1.Age)
    }
    
    

    3、特意声明注意事项!!!

    结构体是值类型,需要使用 new 分配内存

    4、匿名字段,直接看下面代码

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        type Class struct {
            ClassName string
        }
        type Student struct { //定义结构体
            name  string
            age   int
            Class // 定义匿名字段,继承了该结构体的所有字段
        }
        s1 := new(Student) // 定义指向结构体的指针
        s1.ClassName = "xiaomu"
        fmt.Printf("ClassName:%s
    ", s1.ClassName)
    }
    
    

    struct 的方法

    1、在 struct 中定义方法并且使用

    package main
    
    import (
        "fmt"
    )
    
    type Student struct { //定义结构体
        name string
        age  int
    }
    
    func (stu *Student) OutName() { // 定义Student方法
        fmt.Println(stu.name)
    }
    
    func main() {
        s1 := new(Student) // 定义指向结构体的指针
        s1.name = "xaiomu"
        s1.OutName()
    }
    
    

    2、结构体继承结构体,其中被继承结构体的方法全部为继承结构体吸收(吸星大法)

    package main
    
    import (
        "fmt"
    )
    
    type ClassName struct {
        className string
    }
    
    func (cla *ClassName) OutClassName() {
        fmt.Println(cla.className)
    }
    
    type Student struct { //定义结构体
        name      string
        age       int
        ClassName // 继承ClassName结构体的所有
    }
    
    func (stu *Student) OutName() { // 定义Student方法
        fmt.Println(stu.name)
    }
    
    func main() {
        s1 := new(Student) // 定义指向结构体的指针
        s1.className = "xiaomu"
        s1.OutClassName()
    }
    
    

    原文地址

  • 相关阅读:
    Debug和Release区别
    C语言程序_管理系统
    读书的学问
    御姐的含义
    进制的英文书写
    CHM文件无法打开的解决方法
    819代码
    点击链接不跳转或刷新
    MS SqlServer 随机查询并随机排序
    Html背景图
  • 原文地址:https://www.cnblogs.com/php-linux/p/13051255.html
Copyright © 2011-2022 走看看