1.前言
目前goland还会报泛型语法错误,等待更新就好了
这一次的版本更新主要有
-
泛型(Generics) -
模糊测试(Fuzzing) -
工作区(Workspaces) -
20%的性能改进(针对ARM64与PowerPC64而言)
1.18我最期待的就是两功能了,一个是泛型、一个是模糊测试
2.泛型(Generics)
-
The syntax for function and type declarations now accepts type parameters. -
Parameterized functions and types can be instantiated by following them with a list of type arguments in square brackets. -
The new token ~
has been added to the set of operators and punctuation. -
The syntax for Interface types now permits the embedding of arbitrary types (not just type names of interfaces) as well as union and ~T
type elements. Such interfaces may only be used as type constraints. An interface now defines a set of types as well as a set of methods. -
The new predeclared identifier any
is an alias for the empty interface. It may be used instead ofinterface{}
. -
The new predeclared identifier comparable
is an interface that denotes the set of all types which can be compared using==
or!=
. It may only be used as (or embedded in) a type constraint.
演示代码:
func main() {
fmt.Println(sum(1,1))
}
// [] 中声明了一个泛型T支持的类型
func sum[T int | int64 ](x, y T) T {
return x + y
}
因为此处的泛型需要先声明传入的类型,那么如果我们传入不正确的类型呢
func main() {
fmt.Println(sum("1","1"))
}
func sum[T int | int64 ](x, y T) T {
return x + y
}
直接编译报错
go run main.go
# command-line-arguments
./main.go:6:17: string does not implement int|int64
不过每次都在方法的附近加一个[]声明类型,而且如果这个泛型的类型声明太多的话,感觉太丑了,golang也贴心为我们提供了封装的方法
type Number interface {
int | int8 | int16 | int32 | int64 | float32 | float64
}
func main() {
fmt.Println(sum(1,1))
}
func sum[T Number](x, y T) T {
return x + y
}
3.模糊测试(Fuzzing)
模糊测试 (fuzz testing, fuzzing)是一种软件测试技术。其核心思想是將自动或半自动生成的随机数据输入到一个程序中,并监视程序异常,如崩溃,断言(assertion)失败,以发现可能的程序错误,比如内存泄漏。模糊测试常常用于检测软件或计算机系统的安全漏洞。 --wiki(https://zh.wikipedia.org/zh/模糊测试)
官方demo
func FuzzHex(f *testing.F) {
for _, seed := range [][]byte{{}, {0}, {9}, {0xa}, {0xf}, {1, 2, 3, 4}} {
f.Add(seed)
}
f.Fuzz(func(t *testing.T, in []byte) {
enc := hex.EncodeToString(in)
out, err := hex.DecodeString(enc)
if err != nil {
t.Fatalf("%v: decode: %v", in, err)
}
if !bytes.Equal(in, out) {
t.Fatalf("%v: not equal after round trip: %v", in, out)
}
})
}
其他更新
官方1.18文档说明 https://go.dev/doc/go1.18
参考资料
Getting started with fuzzinghttps://go.dev/doc/tutorial/fuzz
Getting started with generics https://go.dev/doc/tutorial/generics
文章评论