go语言中的结构体与方法详解

发布: 2020-06-19 17:44:19
转载
3256 人浏览过

go语言中的结构体与方法详解

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

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\nage:%d\n", 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\nage: %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\n", 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()
}
登录后复制

更多相关知识请关注go语言教程栏目

以上是go语言中的结构体与方法详解的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:cnblogs.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!