10

20.不要在函数参数中使用空接口

 3 years ago
source link: https://segmentfault.com/a/1190000039052071
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文视频地址

为什么要做这一节,有一些小伙伴,把一些代码给我看,说同时写了的代码,参数是interface{}空接口,看不懂,不知道是做什么的,那么我们下面就看看空接口当参数的是不是合适?

// $GOROOT/src/io/io.go
type Reader interface {
        Read(p []byte) (n int, err error)
}

Go编译器通过分析该接口定义得到接口的名称信息以及其方法信息,此接口类型参数赋值时,编译器会根据这些信息对实参进行检查。如果函数或方法的参数类型为空接口interface{},那么,空接口不会提供任何信息给编译器。如果你在函数或方法中使用空接口类型,意味着你不想给编译器提供关于传入参数数据的任何信息,所以,将不会有静态类型语言类型安全检查的--”保障”,你需要自己处理。

标准库里使用interface{}空接口作为参数类型的方法和函数非常少。使用Interface{}作为参数类型的函数和方法主要有两类:

1 容器算法类: sync.Map、list、sort、heap等。

2 格式化日之类: fmt、log等。

上面这些共同的特点就是他们面对的都是未知的类型的数据,所以使用了 interface{},就是Go语言还没有支持泛型的原因,个人认为就是临时方案,如果以后有了泛型,会使用泛型解决。

6Z3QjeU.png!mobile


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK