接口的值的类型
接口变量内部是存储的类型和值的指针,所以并不用是用接口的指针
接口变量也是值传递
指针接受者只能以指针方式使用,值接受者都可以
go 中 取接口的类型有两种方式
switch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18func inspect(dl Downloader) {
switch v := dl.(type) {
case *interfaces.SimpleDownload:
fmt.Println("sim:", v)
case *interfaces.RealDownload:
fmt.Println("real:", v)
}
}
var dl Downloader
dl = &interfaces.SimpleDownload{}
inspect(dl)
dl = &interfaces.RealDownload{}
inspect(dl)
/*
sim: &{}
real: &{}
*/一种是type assertion 或者另外一种叫法是 comma-ok
1
2
3
4
5
6
7
8
9
10
11
12
13var dl Downloader
dl = &interfaces.SimpleDownload{}
if _ ,ok := dl.(*interfaces.SimpleDownload); ok {
fmt.Println("SimpleDownload")
}
dl = &interfaces.RealDownload{}
if _ ,ok := dl.(*interfaces.RealDownload); ok {
fmt.Println("RealDownload")
}
/*
SimpleDownload
RealDownload
*/
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 SHIELD!
评论