mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-19 20:00:35 +08:00
new file: 18.10.md new file: 18.11.md new file: 18.2.md new file: 18.3.md new file: 18.4.md modified: 18.5.md new file: 18.6.md new file: 18.7.md new file: 18.8.md new file: 18.9.md modified: directory.md
38 lines
972 B
Markdown
38 lines
972 B
Markdown
# 18.5 接口
|
||
|
||
(1)如何检测一个值v是否实现了一个接口`Stringer`:
|
||
|
||
```go
|
||
if v, ok := v.(Stringer); ok {
|
||
fmt.Printf("implements String(): %s\n", v.String())
|
||
}
|
||
```
|
||
|
||
(2)如何使用接口实现一个类型分类函数:
|
||
|
||
```go
|
||
func classifier(items ...interface{}) {
|
||
for i, x := range items {
|
||
switch x.(type) {
|
||
case bool:
|
||
fmt.Printf("param #%d is a bool\n", i)
|
||
case float64:
|
||
fmt.Printf("param #%d is a float64\n", i)
|
||
case int, int64:
|
||
fmt.Printf("param #%d is an int\n", i)
|
||
case nil:
|
||
fmt.Printf("param #%d is nil\n", i)
|
||
case string:
|
||
fmt.Printf("param #%d is a string\n", i)
|
||
default:
|
||
fmt.Printf("param #%d’s type is unknown\n", i)
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
## 链接
|
||
|
||
- [目录](directory.md)
|
||
- 上一章:[运算符模板和接口](17.4.md)
|
||
- 下一节:[字符串](18.1.md) |