doutan5724 2017-03-30 18:46
浏览 73
已采纳

用接口进行类型断言不了解它如何

I'm reading "Go Bootcamp" and there is an example in the Chapter 3, page 20 I cannot understand. In this example, in the line printString(s), s is a variable of type fakeString, but in the switch, enters in the "Stringer" case. I'm trying to understand how is this possible. Any help would be appreciated.

The code is:

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")
}
  • 写回答

1条回答 默认 最新

  • dongling2038 2017-03-30 19:02
    关注

    Because the fakeString is a different type than string, but it implements Stringer interface. Every type with given function implements the type. The fakeString contains the String() func so it also implements Stringer interface. This is some kind of fundamental stones of Go.

    Check the built-in libs for Reader interface, it is usually given as an example for this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料