【发布时间】:2017-03-30 18:46:33
【问题描述】:
我正在阅读“Go Bootcamp”,第 3 章第 20 页中有一个示例我无法理解。在此示例中,在 printString(s) 行中,s 是 fakeString 类型的变量,但在 switch 中,输入的是“Stringer”情况。我试图了解这怎么可能。任何帮助,将不胜感激。
代码是:
package main
import "fmt"
type Stringer interface {
String() string
}
type fakeString struct {
content string
}
// function used to implement the Stringer interface
func (s *fakeString) String() string {
return s.content
}
func printString(value interface{}) {
switch str := value.(type) {
case string:
fmt.Println(str)
case Stringer:
fmt.Println(str.String())
}
}
func main() {
s := &fakeString{"Ceci n'est pas un string"}
printString(s)
printString("Hello, Gophers")
}
【问题讨论】:
-
先完成围棋之旅,然后是其他一些教程。
标签: go interface type-assertion