10 | 面向对象

  • 利用方法来模拟面向对象
type student struct{
    name string
    age int8
}
func (s *student) getName() string {
    return s.name
}
func TestClass(t *testing.T){
    stu := student{"fangle",20}
    t.Log(stu.getName())
}
//result : fangle

方法实际上也是函数,只是在声明时在关键字fun和方法之间增加一个参数,这个参数也称之为接收者。

  • 值接收者与指针接收者
type student struct{
    name string
    age int8
}
func (s student) setAge(age int8)  {
    s.age = age
}
func TestClass(t *testing.T){
    stu := student{}
    stu.setAge(21)
    t.Log(stu)
}
//result : {0  } 

值接收者得到了结构体的一份拷贝,方法内的操作不会影响调用者

type student struct{
    name string
    age int8
}
func (s *student) setAge(age int8)  {
    s.age = age
}
func TestClass(t *testing.T){
    stu := student{}
    stu.setAge(21)
    t.Log(stu)
}
//result : { 21}

指针接收者得到了结构体指针的一份拷贝,方法内操作会影响调用者

使用值接收者还是指针接收者,不应该由该方法是否修改了接收到到值来决定。这个决策应该基于该类型到本质

  • 方法的接收者可以是任意自定义类型
type text string
func (t *text) len() int{
    return len(*t)
}
func TestClass(t *testing.T){
    var msg text = "mysql gone away"
    t.Log(msg.len())
}
//result : 15
  • String魔术方法

组合

  • 允许结构体内嵌
type user struct {
    name string
    age int8
}
type vip struct {
    user
    level int8
}
func TestClass(t *testing.T){
    one := vip{
        user {
            name: "fangle",
            age:  20,
        },1,
    }
    t.Log(one,one.name,one.user.name)
}
//result : {{fangle 20} 1} fangle fangle
  • 利用结构体内嵌来实现组合
type header struct {
    meta string
    script string
}
type body struct {
    div string
    table string
    script string
}

type html struct {
    header
    body
    script string
}
func TestClass(t *testing.T){
    doc := html{
        header{"<meta>", "<script0>"},
        body{"<div>","<table>","<script1>"},
        "<script2>",
    }
    t.Log(doc,doc.script)
    t.Log(doc.header.script,doc.body.script)
}
//result :{{<meta> <script0>} {<div> <table> <script1>} <script2>} 
//<script2> <script0> <script1>

如果两个内嵌结构体之间有同名变量,不允许外层结构体直接访问变量,必须显示指定要访问的是那个内嵌结构体的变量

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

推荐阅读更多精彩内容