标签 模板 下的文章

Go泛型真的要来了!最早在Go 1.17版本支持

Go官博今晨发表了Go核心团队两位大神Ian Lance Taylor和Go语言之父之一的Robert Griesemer撰写的文章“The Next Step for Generics”,该文介绍了Go泛型(Go Generics)的最新进展和未来计划。

2019年中旬,在Go 1.13版本发布前夕的GopherCon 2019大会上,Ian Lance Taylor代表Go核心团队做了有关Go泛型进展的介绍。自那以后,Go团队对原先的Go Generics技术草案做了进一步精化,并编写了相关工具让社区gopher体验满足这份设计的Go generics语法,返回建议和意见。经过一年多的思考、讨论、反馈与实践,Go核心团队决定在这份旧设计的基础上另起炉灶,撰写了一份Go Generics的新技术提案:“Type Parameters”。与上一份提案最大的不同在于使用扩展的interface类型替代“Contract”用于对类型参数的约束。

parametric polymorphism((形式)参数多态)是Go此版泛型设计的基本思想。和Go设计思想一致,这种参数多态并不是通过像面向对象语言那种子类型的层次体系实现的,而是通过显式定义结构化的约束实现的。基于这种设计思想,该设计不支持模板元编程(template metaprogramming)和编译期运算。

注意:虽然都称为泛型(generics),但是Go中的泛型(generics)仅是用于狭义地表达带有类型参数(type parameter)的函数或类型,这与其他编程语言中的泛型(generics)在含义上有相似性,但不完全相同。

从目前的情况来看,该版设计十分接近于最终接受的方案,因此作为Go语言鼓吹者这里就和大家一起看看最早将于Go 1.17版本(2021年8月)中加入的Go泛型支持究竟是什么样子的。由于目前关于Go泛型的资料仅限于这份设计文档以及一些关于这份设计的讨论贴,本文内容均来自这些资料。另外最终加入Go的泛型很可能与目前设计文档中提到的有所差异,请各位小伙伴们了解。

1. 通过为type和function增加类型参数(type parameters)的方式实现泛型

Go的泛型主要体现在类型和函数的定义上。

  • 泛型函数(generic function)

Go提案中将带有类型参数(type parameters)的函数称为泛型函数,比如:

func PrintSlice(type T)(s []T) {
    for _, v := range s {
        fmt.Printf("%v ", v)
    }
    fmt.Print("\n")
}

其中,函数名PrintSlice与函数参数列表之间的type T即为类型参数列表。顾名思义,该函数用于打印元素类型为T的切片中的所有元素。使用该函数的时候,除了要传入要打印的切片实参外,还需要为类型参数传入实参(一个类型名),这个过程称为泛型函数的实例化。见下面例子:

// https://go2goplay.golang.org/p/rDbio9c4AQI
package main

import "fmt"

func PrintSlice(type T)(s []T) {
    for _, v := range s {
        fmt.Printf("%v ", v)
    }
    fmt.Print("\n")
}

func main() {
    PrintSlice(int)([]int{1, 2, 3, 4, 5})
    PrintSlice(float64)([]float64{1.01, 2.02, 3.03, 4.04, 5.05})
    PrintSlice(string)([]string{"one", "two", "three", "four", "five"})
}

运行该示例:

1 2 3 4 5
1.01 2.02 3.03 4.04 5.05
one two three four five

但是这种每次都显式指定类型参数实参的使用方式显然有些复杂繁琐,给开发人员带来心智负担和不好的体验。Go编译器是聪明的,大多数使用泛型函数的场景下,编译器都会根据函数参数列表传入的实参类型自动推导出类型参数的实参类型(type inference)。比如将上面例子改为下面这样,程序依然可以输出正确的结果。

// https://go2goplay.golang.org/p/UgHqZ7g4rbo
package main

import "fmt"

func PrintSlice(type T)(s []T) {
    for _, v := range s {
        fmt.Printf("%v ", v)
    }
    fmt.Print("\n")
}

func main() {
    PrintSlice([]int{1, 2, 3, 4, 5})
    PrintSlice([]float64{1.01, 2.02, 3.03, 4.04, 5.05})
    PrintSlice([]string{"one", "two", "three", "four", "five"})
}
  • 泛型类型(generic type)

Go提案中将带有类型参数(type parameters)的类型定义称为泛型类型,比如我们定义一个底层类型为切片类型的新类型:Vector:

type Vector(type T) []T

该Vector(切片)类型中的元素类型为T。和泛型函数一样,使用泛型类型时,我们首先要对其进行实例化,即显式为类型参数赋一个实参值(一个类型名):

//https://go2goplay.golang.org/p/tIZN2if1Wxo

package main

import "fmt"

func PrintSlice(type T)(s []T) {
    for _, v := range s {
        fmt.Printf("%v ", v)
    }
    fmt.Print("\n")
}

type Vector(type T) []T

func main() {
    var vs = Vector(int){1, 2, 3, 4, 5}
    PrintSlice(vs)
}

泛型类型的实例化是必须显式为类型参数传参的,编译器无法自行做类型推导。如果将上面例子中main函数改为如下实现方式:

func main() {
    var vs = Vector{1, 2, 3, 4, 5}
    PrintSlice(vs)
}

则Go编译器会报如下错误:

type checking failed for main
prog.go2:15:11: cannot use generic type Vector(type T) without instantiation

这个错误的意思就是:未实例化(instantiation)的泛型类型Vector(type T)无法使用。

2. 通过扩展了的interface类型对类型参数进行约束和限制

1) 对泛型函数中类型参数的约束与限制

有了泛型函数,我们来实现一个“万能”加法函数:

// https://go2goplay.golang.org/p/t0vXI6heUrT
package main

import "fmt"

func Add(type T)(a, b T) T {
    return a + b
}

func main() {
    c := Add(5, 6)
    fmt.Println(c)
}

运行上述示例:

type checking failed for main
prog.go2:6:9: invalid operation: operator + not defined for a (variable of type T)

什么情况!这么简单的一个函数,Go编译器居然报了这个错误:类型参数T未定义“+”这个操作符运算

在此版Go泛型设计中,泛型函数只能使用类型参数所能实例化出的任意类型都能支持的操作。比如上述Add函数的类型参数type T没有任何约束,它可以被实例化为任何类型。那么这些实例化后的类型是否都支持“+”操作符运算呢?显然不是。因此,编译器针对示例代码中的第六行报了错!

对于像上面Add函数那样的没有任何约束的类型参数实例,Go允许对其进行的操作包括:

  • 声明这些类型的变量;
  • 使用相同类型的值为这些变量赋值;
  • 将这些类型的变量以实参形式传给函数或从作为函数返回值;
  • 取这些变量的地址;
  • 将这些类型的值转换或赋值给interface{}类型变量;
  • 通过类型断言将一个接口值赋值给这类类型的变量;
  • 在type switch块中作为一个case分支;
  • 定义和使用由该类型组成的复合类型,比如:元素类型为该类型的切片;
  • 将该类型传递给一些内置函数,比如new。

那么,我们要让上面的Add函数通过编译器的检查,我们就需要限制其类型参数所能实例化出的类型的范围。比如:仅允许实例化为底层类型(underlying type)为整型类型的类型。上一版Go泛型设计中使用Contract来定义对类型参数的约束,不过由于Contract与interface在概念范畴上有交集,让Gopher们十分困惑,于是在新版泛型设计中,Contract这个关键字被移除了,取而代之的是语法扩展了的interface,即我们使用interface类型来修饰类型参数以实现对其可实例化出的类型集合的约束。我们来看下面例子:

// https://go2goplay.golang.org/p/kMxZI2vIsk-
package main

import "fmt"

type PlusableInteger interface {
    type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64
}

func Add(type T PlusableInteger)(a, b T) T {
    return a + b
}

func main() {
    c := Add(5, 6)
    fmt.Println(c)
}

运行该示例:

11

如果我们在main函数中写下如下代码:

    f := Add(3.65, 7.23)
    fmt.Println(f)

我们将得到如下编译错误:

type checking failed for main
prog.go2:20:7: float64 does not satisfy PlusableInteger (float64 not found in int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64)

我们看到:该提案扩展了interface语法,新增了类型列表(type list)表达方式,专用于对类型参数进行约束。以该示例为例,如果编译器通过类型推导得到的类型在PlusableInteger这个接口定义的类型列表(type list)中,那么编译器将允许这个类型参数实例化;否则就像Add(3.65, 7.23)那样,推导出的类型为float64,该类型不在PlusableInteger这个接口定义的类型列表(type list)中,那么类型参数实例化将报错!

注意:定义中带有类型列表的接口将无法用作接口变量类型,比如下面这个示例:

// https://go2goplay.golang.org/p/RchnTw73VMo
package main

type PlusableInteger interface {
    type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64
}

func main() {
    var n int = 6
    var i PlusableInteger
    i = n
    _ = i
}

编译器会报如下错误:

type checking failed for main
prog.go2:9:8: interface type for variable cannot contain type constraints (int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64)

我们还可以用interface的原生语义对类型参数进行约束,看下面例子:

// https://go2goplay.golang.org/p/hyTbglTLoIn
package main

import (
    "fmt"
    "strconv"
)

type StringInt int

func (i StringInt) String() string {
    return strconv.Itoa(int(i))
}

type Stringer interface {
    String() string
}

func Stringify(type T Stringer)(s []T) (ret []string) {
    for _, v := range s {
        ret = append(ret, v.String())
    }
    return ret
}

func main() {
    fmt.Println(Stringify([]StringInt{1, 2, 3, 4, 5}))
}

运行该示例:

[1 2 3 4 5]

如果我们在main函数中写下如下代码:

func main() {
    fmt.Println(Stringify([]int{1, 2, 3, 4, 5}))
}

那么我们将得到下面的编译器错误输出:

type checking failed for main
prog.go2:27:2: int does not satisfy Stringer (missing method String)

我们看到:只有实现了Stringer接口的类型才会被允许作为实参传递给Stringify泛型函数的类型参数并成功实例化。

我们还可以结合interface的类型列表(type list)和方法列表一起对类型参数进行约束,看下面示例:

// https://go2goplay.golang.org/p/tchwW6mPL7_d
package main

import (
    "fmt"
    "strconv"
)

type StringInt int

func (i StringInt) String() string {
    return strconv.Itoa(int(i))
}

type SignedIntStringer interface {
    type int, int8, int16, int32, int64
    String() string
}

func Stringify(type T SignedIntStringer)(s []T) (ret []string) {
    for _, v := range s {
        ret = append(ret, v.String())
    }
    return ret
}

func main() {
    fmt.Println(Stringify([]StringInt{1, 2, 3, 4, 5}))
}

在该示例中,用于对泛型函数的类型参数进行约束的SignedIntStringer接口既包含了类型列表,也包含方法列表,这样类型参数的实参类型既要在SignedIntStringer的类型列表中,也要实现了SignedIntStringer的String方法。

如果我们将上面的StringInt的底层类型改为uint:

type StringInt uint

那么我们将得到下面的编译器错误输出:

type checking failed for main
prog.go2:27:14: StringInt does not satisfy SignedIntStringer (uint not found in int, int8, int16, int32, int64)

2) 引入comparable预定义类型约束

由于Go泛型设计选择了不支持运算操作符重载,因此,我们即便对interface做了语法扩展,依然无法表达类型是否支持==!=。为了解决这个表达问题,这份新设计提案中引入了一个新的预定义类型约束:comparable。我们看下面例子:

// https://go2goplay.golang.org/p/tea39NqwZGC
package main

import (
    "fmt"
)

// Index returns the index of x in s, or -1 if not found.
func Index(type T comparable)(s []T, x T) int {
    for i, v := range s {
        // v and x are type T, which has the comparable
        // constraint, so we can use == here.
        if v == x {
            return i
        }
    }
    return -1
}

type Foo struct {
    a string
    b int
}

func main() {
    fmt.Println(Index([]int{1, 2, 3, 4, 5}, 3))
    fmt.Println(Index([]string{"a", "b", "c", "d", "e"}, "d"))
    pos := Index(
        []Foo{
            Foo{"a", 1},
            Foo{"b", 2},
            Foo{"c", 3},
            Foo{"d", 4},
            Foo{"e", 5},
        }, Foo{"b", 2})
    fmt.Println(pos)
}

运行该示例:

2
3
1

我们看到Go的原生支持比较的类型,诸如整型、字符串以及由这些类型组成的复合类型(如结构体)均可以直接作为实参传给由comparable约束的类型参数。comparable可以看成一个由Go编译器特殊处理的、包含由所有内置可比较类型组成的type list的interface类型。我们可以将其嵌入到其他作为约束的接口类型定义中:

type ComparableStringer interface {
    comparable
    String() string
}

只有支持比较的类型且实现了String方法,才能满足ComparableStringer的约束。

3) 对泛型类型中类型参数的约束

和对泛型函数中类型参数的约束方法一样,我们也可以对泛型类型的类型参数以同样方法做同样的约束,看下面例子:

// https://go2goplay.golang.org/p/O-YpTcW-tPu

// Package set implements sets of any comparable type.
package main

// Set is a set of values.
type Set(type T comparable) map[T]struct{}

// Make returns a set of some element type.
func Make(type T comparable)() Set(T) {
    return make(Set(T))
}

// Add adds v to the set s.
// If v is already in s this has no effect.
func (s Set(T)) Add(v T) {
    s[v] = struct{}{}
}

// Delete removes v from the set s.
// If v is not in s this has no effect.
func (s Set(T)) Delete(v T) {
    delete(s, v)
}

// Contains reports whether v is in s.
func (s Set(T)) Contains(v T) bool {
    _, ok := s[v]
    return ok
}

// Len reports the number of elements in s.
func (s Set(T)) Len() int {
    return len(s)
}

// Iterate invokes f on each element of s.
// It's OK for f to call the Delete method.
func (s Set(T)) Iterate(f func(T)) {
    for v := range s {
        f(v)
    }
}

func main() {
    s := Make(int)()

    // Add the value 1,11,111 to the set s.
    s.Add(1)
    s.Add(11)
    s.Add(111)

    // Check that s does not contain the value 11.
    if s.Contains(11) {
        println("the set contains 11")
    }
}

运行该示例:

the set contains 11

这个示例定义了一个数据结构:Set。该Set中的元素是有约束的:必须支持可比较。对应到代码中,我们用comparable作为泛型类型Set的类型参数的约束。

4) 关于泛型类型的方法

泛型类型和普通类型一样,也可以定义自己的方法。但泛型类型的方法目前不支持除泛型类型自身的类型参数之外的其他类型参数了。我们看下面例子:

// https://go2goplay.golang.org/p/JipsxG7jeCN

// Package set implements sets of any comparable type.
package main

// Set is a set of values.
type Set(type T comparable) map[T]struct{}

// Make returns a set of some element type.
func Make(type T comparable)() Set(T) {
    return make(Set(T))
}

// Add adds v to the set s.
// If v is already in s this has no effect.
func (s Set(T)) Add(v T) {
    s[v] = struct{}{}
}

func (s Set(T)) Method1(type P)(v T, p P) {

}

func main() {
    s := Make(int)()
    s.Add(1)
    s.Method1(10, 20)
}

在这个示例中,我们新定义的Method1除了在参数列表中使用泛型类型Set的类型参数T之外,又接受了一个类型参数P。执行该示例:

type checking failed for main
prog.go2:18:24: methods cannot have type parameters

我们看到编译器给出错误:泛型类型的方法不能再有其他类型参数。目前提案仅是暂时不支持额外的类型参数(如果支持,会让语言规范和实现都变得异常复杂),Go核心团队也会听取社区反馈的意见,直到大家都认为支持额外类型参数是有必要的,那么后续会重新添加。

5) type *T Constraint

上面我们一直采用的对类型参数的约束形式是:

type T Constraint

假设调用泛型函数时某类型A要作为T的实参传入,A必须实现Constraint(接口)。

如果我们将上面对类型参数的约束形式改为:

type *T Constraint

那么这将意味着类型A要作为T的实参传入,*A必须满足Constraint(接口)。并且Constraint中的所有方法(如果有的话)都仅能通过*A实例调用。我们来看下面示例:

// https://go2goplay.golang.org/p/g3cwgguCmUo
package main

import (
    "fmt"
    "strconv"
)

type Setter interface {
    Set(string)
}

func FromStrings(type *T Setter)(s []string) []T {
    result := make([]T, len(s))
    for i, v := range s {
        result[i].Set(v)
    }
    return result
}

// Settable is a integer type that can be set from a string.
type Settable int

// Set sets the value of *p from a string.
func (p *Settable) Set(s string) {
    i, _ := strconv.Atoi(s) // real code should not ignore the error
    *p = Settable(i)
}

func main() {
    nums := FromStrings(Settable)([]string{"1", "2"})
    fmt.Println(nums)
}

运行该示例:

[1 2]

我们看到Settable的方法集合是空的,而*Settable的方法集合(method set)包含了Set方法。因此,*Settable是满足Setter对FromStrings函数的类型参数的约束的。

而如果我们直接使用type T Setter,那么编译器将给出下面错误:

type checking failed for main
prog.go2:30:22: Settable does not satisfy Setter (missing method Set)

如果我们使用type T Setter并结合使用FromStrings(*Settable),那么程序运行会panic。

https://go2goplay.golang.org/p/YLe2d78aSz-

3. 性能影响

根据这份技术提案中关于泛型函数和泛型类型实现的说明,Go会使用基于接口的方法来编译泛型函数(generic function),这将优化编译时间,因为该函数仅会被编译一次。但是会有一些运行时代价。

对于每个类型参数集,泛型类型(generic type)可能会进行多次编译。这将延长编译时间,但是不会产生任何运行时代价。编译器还可以选择使用类似于接口类型的方法来实现泛型类型,使用专用方法访问依赖于类型参数的每个元素。

4. 小结

Go泛型方案的即将定型即好也不好。Go向来以简洁著称,增加加泛型,无论采用什么技术方案,都会增加Go的复杂性,提升其学习门槛,代码可读性也会下降。但在某些场合(比如实现container数据结构及对应算法库等),使用泛型却又能简化实现。

在这份提案中,Go核心团队也给出如下期望:

We expect that most packages will not define generic types or functions, but many packages are likely to use generic types or functions defined elsewhere

我们期望大多数软件包不会定义泛型类型或函数,但是许多软件包可能会使用在其他地方定义的泛型类型或函数。

并且提案提到了会在Go标准库中增加一些新包,已实现基于泛型的标准数据结构(slice、map、chan、math、list/ring等)、算法(sort、interator)等,gopher们只需调用这些包提供的API即可。

另外该提案的一大优点就是与Go1兼容,我们可能永远不会使用Go2这个版本号了。

go核心团队提供了可实践该方案语法的playground:https://go2goplay.golang.org/,大家可以一边研读技术提案,一边编写代码进行实验验证。


我的网课“Kubernetes实战:高可用集群搭建、配置、运维与应用”在慕课网上线了,感谢小伙伴们学习支持!

我爱发短信:企业级短信平台定制开发专家 https://tonybai.com/
smspush : 可部署在企业内部的定制化短信平台,三网覆盖,不惧大并发接入,可定制扩展; 短信内容你来定,不再受约束, 接口丰富,支持长短信,签名可选。

2020年4月8日,中国三大电信运营商联合发布《5G消息白皮书》,51短信平台也会全新升级到“51商用消息平台”,全面支持5G RCS消息。

著名云主机服务厂商DigitalOcean发布最新的主机计划,入门级Droplet配置升级为:1 core CPU、1G内存、25G高速SSD,价格5$/月。有使用DigitalOcean需求的朋友,可以打开这个链接地址:https://m.do.co/c/bff6eed92687 开启你的DO主机之路。

Gopher Daily(Gopher每日新闻)归档仓库 – https://github.com/bigwhite/gopherdaily

我的联系方式:

微博:https://weibo.com/bigwhite20xx
微信公众号:iamtonybai
博客:tonybai.com
github: https://github.com/bigwhite

微信赞赏:
img{512x368}

商务合作方式:撰稿、出书、培训、在线课程、合伙创业、咨询、广告合作。

Go 1.6中值得关注的几个变化

北京时间2016年2月18日凌晨,在Go 1.5发布 半年后,Go 1.6正式Release 了。与Go 1.5的“惊天巨变”(主要指Go自举)相比,Go 1.6的Change 算是很小的了,当然这也与Go 1.6的dev cycle过于短暂有关。但Go社区对此次发布却甚是重视,其热烈程度甚至超出了Go 1.5。在Dave Cheney的倡导 下,Gophers们在全球各地举行了Go 1.6 Release Party。 Go Core Team也在Reddit上开了一个AMA – Ask Me Anything,RobPike、Russ Cox(Rsc)、Bradfitz等Go大神齐上阵,对广大Gophers们在24hour内的问题有问必答。

言归正传,我们来看看Go 1.6中哪些变化值得我们关注。不过在说变化之前,我们先提一嘴Go 1.6没变的,那就是Go语言的language specification,依旧保持Go 1兼容不变。预计在未来的几个stable release版本中,我们也不会看到Go language specification有任何改动。

一、cgo

cgo的变化在于:
1、定义了在Go code和C code间传递Pointer,即C code与Go garbage collector共存的rules和restriction;
2、在runtime加入了对违规传递的检查,检查的开关和力度由GODEBUG=cgocheck=1[0,2]控制。1是默认;0是关闭检 查;2是更全面彻底但代价更高的检查。

这个Proposal是由Ian Lance Taylor提出的。大致分为两种情况:

(一) Go调用C Code时

Go调用C Code时,Go传递给C Code的Go Pointer所指的Go Memory中不能包含任何指向Go Memory的Pointer。我们分为几种情况来探讨一下:

1、传递一个指向Struct的指针

//cgo1_struct.go
package main

/*
#include <stdio.h>
struct Foo{
    int a;
    int *p;
};

void plusOne(struct Foo *f) {
    (f->a)++;
    *(f->p)++;
}
*/
import "C"
import "unsafe"
import "fmt"

func main() {
    f := &C.struct_Foo{}
    f.a = 5
    f.p = (*C.int)((unsafe.Pointer)(new(int)))
    //f.p = &f.a

    C.plusOne(f)
    fmt.Println(int(f.a))
}

从cgo1_struct.go代码中可以看到,Go code向C code传递了一个指向Go Memory(Go分配的)指针f,但f指向的Go Memory中有一个指针p指向了另外一处Go Memory: new(int),我们来run一下这段代码:

$go run cgo1_struct.go
# command-line-arguments
./cgo1_struct.go:12:2: warning: expression result unused [-Wunused-value]
panic: runtime error: cgo argument has Go pointer to Go pointer

goroutine 1 [running]:
panic(0x4068400, 0xc82000a110)
    /Users/tony/.bin/go16/src/runtime/panic.go:464 +0x3e6
main.main()
    /Users/tony/test/go/go16/cgo/cgo1_struct.go:24 +0xb9
exit status 2

代码出现了Panic,并提示:“cgo argument has Go pointer to Go pointer”。我们的代码违背了Cgo Pointer传递规则,即便让f.p指向struct自身内存也是不行的,比如f.p = &f.a。

2、传递一个指向struct field的指针

按照rules中的说明,如果传递的是一个指向struct field的指针,那么”Go Memory”专指这个field所占用的内存,即便struct中有其他field指向其他Go memory也不打紧:

//cgo1_structfield.go
package main

/*
#include <stdio.h>
struct Foo{
    int a;
    int *p;
};

void plusOne(int *i) {
    (*i)++;
}
*/
import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    f := &C.struct_Foo{}
    f.a = 5
    f.p = (*C.int)((unsafe.Pointer)(new(int)))

    C.plusOne(&f.a)
    fmt.Println(int(f.a))
}

上述程序的运行结果:

$go run cgo1_structfield.go
6

3、传递一个指向slice or array中的element的指针

和传递struct field不同,传递一个指向slice or array中的element的指针时,需要考虑的Go Memory的范围不仅仅是这个element,而是整个Array或整个slice背后的underlying array所占用的内存区域,要保证这个区域内不包含指向任意Go Memory的指针。我们来看代码示例:

//cgo1_sliceelem.go
package main

/*
#include <stdio.h>
void plusOne(int **i) {
    (**i)++;
}
*/
import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    sl := make([]*int, 5)
    var a int = 5
    sl[1] = &a
    C.plusOne((**C.int)((unsafe.Pointer)(&sl[0])))
    fmt.Println(sl[0])
}

从这个代码中,我们看到我们传递的是slice的第一个element的地址,即&sl[0]。我们并未给sl[0]赋值,但sl[1] 被赋值为另外一块go memory的address(&a),当我们将&sl[0]传递给plusOne时,执行结果如下:

$go run cgo1_sliceelem.go
panic: runtime error: cgo argument has Go pointer to Go pointer

goroutine 1 [running]:
panic(0x40dbac0, 0xc8200621d0)
    /Users/tony/.bin/go16/src/runtime/panic.go:464 +0x3e6
main.main()
    /Users/tony/test/go/go16/cgo/cgo1_sliceelem.go:19 +0xe4
exit status 2

由于违背规则,因此runtime panic了。

(二) C调用Go Code时

1、C调用的Go函数不能返回指向Go分配的内存的指针

我们看下面例子:

//cgo2_1.go

package main

// extern int* goAdd(int, int);
//
// static int cAdd(int a, int b) {
//     int *i = goAdd(a, b);
//     return *i;
// }
import "C"
import "fmt"

//export goAdd
func goAdd(a, b C.int) *C.int {
    c := a + b
    return &c
}

func main() {
    var a, b int = 5, 6
    i := C.cAdd(C.int(a), C.int(b))
    fmt.Println(int(i))
}

可以看到:goAdd这个Go函数返回了一个指向Go分配的内存(&c)的指针。运行上述代码,结果如下:

$go run cgo2_1.go
panic: runtime error: cgo result has Go pointer

goroutine 1 [running]:
panic(0x40dba40, 0xc82006e1c0)
    /Users/tony/.bin/go16/src/runtime/panic.go:464 +0x3e6
main._cgoexpwrap_872b2f2e7532_goAdd.func1(0xc820049d98)
    command-line-arguments/_obj/_cgo_gotypes.go:64 +0x3a
main._cgoexpwrap_872b2f2e7532_goAdd(0x600000005, 0xc82006e19c)
    command-line-arguments/_obj/_cgo_gotypes.go:66 +0x89
main._Cfunc_cAdd(0x600000005, 0x0)
    command-line-arguments/_obj/_cgo_gotypes.go:45 +0x41
main.main()
    /Users/tony/test/go/go16/cgo/cgo2_1.go:20 +0x35
exit status 2

2、Go code不能在C分配的内存中存储指向Go分配的内存的指针

下面的例子模拟了这一情况:

//cgo2_2.go
package main

// #include <stdlib.h>
// extern void goFoo(int**);
//
// static void cFoo() {
//     int **p = malloc(sizeof(int*));
//     goFoo(p);
// }
import "C"

//export goFoo
func goFoo(p **C.int) {
    *p = new(C.int)
}

func main() {
    C.cFoo()
}

不过针对此例,默认的GODEBUG=cgocheck=1偏是无法check出问题。我们将GODEBUG=cgocheck改为=2试试:

$GODEBUG=cgocheck=2 go run cgo2_2.go
write of Go pointer 0xc82000a0f8 to non-Go memory 0x4300000
fatal error: Go pointer stored into non-Go memory

runtime stack:
runtime.throw(0x4089800, 0x24)
    /Users/tony/.bin/go16/src/runtime/panic.go:530 +0x90
runtime.cgoCheckWriteBarrier.func1()
    /Users/tony/.bin/go16/src/runtime/cgocheck.go:44 +0xae
runtime.systemstack(0x7fff5fbff8c0)
    /Users/tony/.bin/go16/src/runtime/asm_amd64.s:291 +0x79
runtime.mstart()
    /Users/tony/.bin/go16/src/runtime/proc.go:1048
... ...
goroutine 17 [syscall, locked to thread]:
runtime.goexit()
    /Users/tony/.bin/go16/src/runtime/asm_amd64.s:1998 +0x1
exit status 2

果真runtime panic: write of Go pointer 0xc82000a0f8 to non-Go memory 0×4300000

二、HTTP/2

HTTP/2原本是bradfitz维护的x项目,之前位于golang.org/x/net/http2包中,Go 1.6无缝合入Go标准库net/http包中。并且当你你使用https时,client和server端将自动默认使用HTTP/2协议。

HTTP/2与HTTP1.x协议不同在于其为二进制协议,而非文本协议,性能自是大幅提升。HTTP/2标准已经发布,想必未来若干年将大行其道。

HTTP/2较为复杂,这里不赘述,后续maybe会单独写一篇GO和http2的文章说明。

三、Templates

由于不开发web,templates我日常用的很少。这里粗浅说说templates增加的两个Feature

trim空白字符

Go templates的空白字符包括:空格、水平tab、回车和换行符。在日常编辑模板时,这些空白尤其难于处理,由于是对beatiful format和code readabliity有“强迫症”的同学,更是在这方面话费了不少时间。

Go 1.6提供了{{-和-}}来帮助大家去除action前后的空白字符。下面的例子很好的说明了这一点:

//trimwhitespace.go
package main

import (
    "log"
    "os"
    "text/template"
)

var items = []string{"one", "two", "three"}

func tmplbefore15() {
    var t = template.Must(template.New("tmpl").Parse(`
    <ul>
    {{range . }}
        <li>{{.}}</li>
    {{end }}
    </ul>
    `))

    err := t.Execute(os.Stdout, items)
    if err != nil {
        log.Println("executing template:", err)
    }
}

func tmplaftergo16() {
    var t = template.Must(template.New("tmpl").Parse(`
    <ul>
    {{range . -}}
        <li>{{.}}</li>
    {{end -}}
    </ul>
    `))

    err := t.Execute(os.Stdout, items)
    if err != nil {
        log.Println("executing template:", err)
    }
}

func main() {
    tmplbefore15()
    tmplaftergo16()
}

这个例子的运行结果:

$go run trimwhitespace.go

    <ul>

        <li>one</li>

        <li>two</li>

        <li>three</li>

    </ul>

    <ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
    </ul>

block action

block action提供了一种在运行时override已有模板形式的能力。

package main

import (
    "log"
    "os"
    "text/template"
)

var items = []string{"one", "two", "three"}

var overrideItemList = `
{{define "list" -}}
    <ul>
    {{range . -}}
        <li>{{.}}</li>
    {{end -}}
    </ul>
{{end}}
`

var tmpl = `
    Items:
    {{block "list" . -}}
    <ul>
    {{range . }}
        <li>{{.}}</li>
    {{end }}
    </ul>
    {{end}}
`

var t *template.Template

func init() {
    t = template.Must(template.New("tmpl").Parse(tmpl))
}

func tmplBeforeOverride() {
    err := t.Execute(os.Stdout, items)
    if err != nil {
        log.Println("executing template:", err)
    }
}

func tmplafterOverride() {
    t = template.Must(t.Parse(overrideItemList))
    err := t.Execute(os.Stdout, items)
    if err != nil {
        log.Println("executing template:", err)
    }
}

func main() {
    fmt.Println("before override:")
    tmplBeforeOverride()
    fmt.Println("after override:")
    tmplafterOverride()
}

原模板tmpl中通过block action定义了一处名为list的内嵌模板锚点以及初始定义。后期运行时通过re-parse overrideItemList达到修改模板展示形式的目的。

上述代码输出结果:

$go run blockaction.go
before override:

    Items:
    <ul>

        <li>one</li>

        <li>two</li>

        <li>three</li>

    </ul>

after override:

    Items:
    <ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
    </ul>

四、Runtime

降低大内存使用时的GC latency

Go 1.5.x用降低一些吞吐量的代价换取了10ms以下的GC latency。不过针对Go 1.5,官方给出的benchmark图中,内存heap size最多20G左右。一旦超过20G,latency将超过10ms,也许会线性增长。
在Go 1.6中,官方给出的benchmark图中当内存heap size在200G时,GC latency依旧可以稳定在10ms;在heap size在20G以下时,latency降到了6ms甚至更小。

panic info

Go 1.6之前版本,一旦程序以panic方式退出,runtime便会将所有goroutine的stack信息打印出来:

$go version
go version go1.5.2 darwin/amd64
[ ~/test/go/go16/runtime]$go run panic.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x20d5]

goroutine 1 [running]:
main.main()
    /Users/tony/test/go/go16/runtime/panic.go:19 +0x95

goroutine 4 [select (no cases)]:
main.main.func1(0x8200f40f0)
    /Users/tony/test/go/go16/runtime/panic.go:13 +0x26
created by main.main
    /Users/tony/test/go/go16/runtime/panic.go:14 +0x72
... ...

而Go 1.6后,Go只会打印正在running的goroutine的stack信息,因此它才是最有可能造成panic的真正元凶:

go 1.6:
$go run panic.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x20d5]

goroutine 1 [running]:
panic(0x61e80, 0x8200ee0c0)
    /Users/tony/.bin/go16/src/runtime/panic.go:464 +0x3e6
main.main()
    /Users/tony/test/go/go16/runtime/panic.go:19 +0x95
exit status 2

map race detect

Go原生的map类型是goroutine-unsafe的,长久以来,这给很多Gophers带来了烦恼。这次Go 1.6中Runtime增加了对并发访问map的检测以降低gopher们使用map时的心智负担。

这里借用了Francesc Campoy在最近一期”The State of Go”中的示例程序:

package main

import "sync"

func main() {
    const workers = 100

    var wg sync.WaitGroup
    wg.Add(workers)
    m := map[int]int{}
    for i := 1; i <= workers; i++ {
        go func(i int) {
            for j := 0; j < i; j++ {
                m[i]++
            }
            wg.Done()
        }(i)
    }
    wg.Wait()
}

执行结果:

$ go run map.go
fatal error: concurrent map writes
fatal error: concurrent map writes
... ...

这里在双核i5 mac air下亲测时,发现当workers=2,3,4均不能检测出race。当workers >= 5时可以检测到。

五、其他

手写parser替代yacc生成的parser

这个变化对Gopher们是透明的,但对于Go compiler本身却是十分重要的。

Robert Riesemer在Go 1.6代码Freezing前commit了手写Parser,以替代yacc生成的parser。在AMA上RobPike给出了更换Parser的些许理由:
1、Go compiler可以少维护一个yacc工具,这样更加cleaner;
2、手写Parser在性能上可以快那么一点点。

Go 1.6中GO15VENDOREXPERIMENT将默认开启

根据当初在Go 1.5中引入vendor时的计划,Go 1.6中GO15VENDOREXPERIMENT将默认开启。这显然会导致一些不兼容的情况出现:即如果你的代码在之前并未使用vendor机制,但目录组织中有vendor目录。Go Core team给出的解决方法就是删除vendor目录或改名。

遗留问题是否解决

Go 1.5发布后,曾经发现两个问题,直到Go 1.5.3版本发布也未曾解决,那么Go 1.6是否解决了呢?我们来验证一下。

internal问题

该问题的具体细节可参看我在go github上提交的issue 12217,我在自己的experiments中提交了问题的验证环境代码,这次我们使用Go 1.6看看internal问题是否还存在:

$cd $GOPATH/src/github.com/bigwhite/experiments/go15-internal-issue-12217
$cd otherpkg/
$go build main.go
package main
    imports github.com/bigwhite/experiments/go15-internal-issue-12217/mypkg/internal/foo: use of internal package not allowed

这回go compiler给出了error,而不是像之前版本那样顺利编译通过。看来这个问题是fix掉了。

GOPATH之外vendor机制是否起作用的问题

我们先建立实验环境:

$tree
.
└── testvendor
    └── src
        └── proj1
            ├── main.go
            └── vendor
                └── github.com
                    └── bigwhite
                        └── foo
                            └── foolib.go

进入proj1,build main.go

go build main.go
main.go:3:8: cannot find package "github.com/bigwhite/foo" in any of:
    /Users/tony/.bin/go16/src/github.com/bigwhite/foo (from $GOROOT)
    /Users/tony/Test/GoToolsProjects/src/github.com/bigwhite/foo (from $GOPATH)

go 1.6编译器没有关注同路径下的vendor目录,build失败。

我们设置GOPATH=xxx/testvendor后,再来build:

$export GOPATH=~/Test/go/go16/others/testvendor
$go run main.go
Hello from temp vendor

这回编译运行ok。

由此看来,Go 1.6 vendor在GOPATH外依旧不生效。

六、小结

Go 1.6标准库细微变化还是有很多的,在Go 1.6 Release Notes中可细细品味。

Go 1.6的编译速度、编译出的程序的运行性能与Go 1.5.x也大致无二异。

另外本文实现环境如下:

go version go1.6 darwin/amd64
Darwin tonydeair-2.lan 13.1.0 Darwin Kernel Version 13.1.0: Thu Jan 16 19:40:37 PST 2014; root:xnu-2422.90.20~2/RELEASE_X86_64 x86_64

实验代码可在这里下载。

如发现本站页面被黑,比如:挂载广告、挖矿等恶意代码,请朋友们及时联系我。十分感谢! Go语言第一课 Go语言精进之路1 Go语言精进之路2 商务合作请联系bigwhite.cn AT aliyun.com

欢迎使用邮件订阅我的博客

输入邮箱订阅本站,只要有新文章发布,就会第一时间发送邮件通知你哦!

这里是 Tony Bai的个人Blog,欢迎访问、订阅和留言! 订阅Feed请点击上面图片

如果您觉得这里的文章对您有帮助,请扫描上方二维码进行捐赠 ,加油后的Tony Bai将会为您呈现更多精彩的文章,谢谢!

如果您希望通过微信捐赠,请用微信客户端扫描下方赞赏码:

如果您希望通过比特币或以太币捐赠,可以扫描下方二维码:

比特币:

以太币:

如果您喜欢通过微信浏览本站内容,可以扫描下方二维码,订阅本站官方微信订阅号“iamtonybai”;点击二维码,可直达本人官方微博主页^_^:
本站Powered by Digital Ocean VPS。
选择Digital Ocean VPS主机,即可获得10美元现金充值,可 免费使用两个月哟! 著名主机提供商Linode 10$优惠码:linode10,在 这里注册即可免费获 得。阿里云推荐码: 1WFZ0V立享9折!


View Tony Bai's profile on LinkedIn
DigitalOcean Referral Badge

文章

评论

  • 正在加载...

分类

标签

归档



View My Stats