go结构体与方法

go结构体至关于python中类的概念

结构体用来定义复杂的数据结构,存储不少相同的字段属性python

一、结构体的定义以及简单实用数据结构

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\nage:%d\n", s1.name, s1.age) }

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

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

经过如下方式获取存储的值spa

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

二、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\nage: %d", s1.Name, s1.Age) }

三、特地声明注意事项!!!code

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

四、匿名字段,直接看下面代码继承

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\n", s1.ClassName) }

struct的方法

一、在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() }

二、结构体继承结构体,其中被继承结构体的方法所有为继承结构体吸取(吸星大法)string

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() }
相关文章
相关标签/搜索