Golang学习摘录(三)

来源:互联网 发布:meltwater 知乎 编辑:程序博客网 时间:2024/04/28 05:09

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 Counterc2.AutoAdd()//Counter也能找到*Counter的方法
    }

2.继承

golang继承很隐晦,类型的聚合从而达到方法的继承。比如Mutex类型有两个方法,Lock和Unlock.
type Mutex struct {    //省略其字段}func (m *Mutex) Lock() {    //省略其实现}func (m *Mutex)Unlock() {    //省略其实现}
现在我们通过以下两种方式创建新的数据类型
type NewMutex Mutextype 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绑定,并行执行了,就会取消此设置项。
0 0
原创粉丝点击