Files
the-way-to-go_ZH_CN/eBook/18.5.md
songleo bc390fa872 modified: eBook/18.11.md
modified:   eBook/18.5.md
	modified:   eBook/18.6.md
	modified:   eBook/18.8.md
	modified:   eBook/18.9.md
2016-01-03 22:45:20 +08:00

38 lines
950 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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 #%ds type is unknown\n", i)
}
}
}
```
## 链接
- [目录](directory.md)
- 上一节:[结构体](18.4.md)
- 下一节:[函数](18.6.md)