加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang学习摘录(三)

发布时间:2020-12-16 18:33:53 所属栏目:大数据 来源:网络整理
导读:golang学习笔记(三) 方法(Method sets) The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T

golang学习笔记(三)

  1. 方法(Method sets)

    The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is,it also contains the method set of T).

    翻译一下:类型T仅仅包含类型T接收的方法,类型T的指针(也就是*T)既包含T接收的也包含*T接收的方法。但是实际结果是,二者并不区分,相互之间均包含,可能是文档是旧的,跟不上语言发布新版。

    type Counter struct {
        v int
    }
    func (c Counter) AutoAdd() {//接收者是Counter
        c.v++
        fmt.Println(c.v)
    }
    func main() {
        //var c Counter结果同下
        c := new(Counter)//new返回指针,&File{}也是指针,c类型是*Counter
        c.AutoAdd()//*Counter包含Counter接收的方法
        c.AutoAdd()//由于接收者不是指针,每次调用c都是传递拷贝,所以两次结果都是1
    }
    

    type Counter struct {
        v int
    }
    func (c *Counter) AutoAdd() {//接收者是*Counter指针
        c.v++
        fmt.Println(c.v)
    }
    func main() {
        c := new(Counter)//new返回指针,c类型是*Counter
        c.AutoAdd()
        c.AutoAdd()//由于接收者是指针,所以两次结果是1,2
    
    
    }c2 := Counter{}//返回类型是Counter
    //或者var c2 Counter
    c2.AutoAdd()//Counter也能找到*Counter的方法

2.继承

golang继承很隐晦,类型的聚合从而达到方法的继承。比如Mutex类型有两个方法,Lock和Unlock.
type Mutex struct {
    //省略其字段
}
func (m *Mutex) Lock() {
    //省略其实现
}
func (m *Mutex)Unlock() {
    //省略其实现
}
现在我们通过以下两种方式创建新的数据类型
type NewMutex Mutex
type PrintableMutex struct {Mutex}
NewMutex是Mutex别名,不同的类型,但是NewMutex不包含任何Mutex的方法,也就是NewMutex的方法是空的。但是PrintableMutex从Mutex继承了以上2个方法,并且绑定到PrintableMutex匿名字段Mutex上。

对于接口类型,别名即可继承。
type Block interface {
    BlockSize() int
    Encrypt(src,dst []byte)
    Decrypt(src,dst []byte)
}
type MyBlock Block //MyBlock继承Block的3个方法

3.goroutine并行执行

并发,并行二者区别,可以自行百度。goroutine是并发执行的,但是默认情况下,不是并行运行,也就是说任意时刻,只有一个goroutine运行。可以设置runtime.GOMAXPROCS来设置几个goroutine并行执行,一般设置为CPU个数,每个goroutine分到一个CPU。后续版本golang改进调度器后,能实现自动CPU绑定,并行执行了,就会取消此设置项。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读