【问题标题】:Go type assertion with interface don't understand how does it带接口的 Go 类型断言不明白它是怎么做的
【发布时间】: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


【解决方案1】:

因为 fakeString 是不同于字符串的类型,但它实现了 Stringer 接口。每个具有给定函数的类型都实现了该类型。 fakeString 包含 String() 函数,因此它还实现了 Stringer 接口。这是围棋的某种基石。

检查Reader接口的内置库,通常作为示例给出。

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 2019-11-21
    • 2016-05-26
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2023-04-03
    相关资源
    最近更新 更多