Go类型断言与接口,不理解它的工作原理。

huangapple go评论72阅读模式
英文:

Go type assertion with interface don't understand how does it

问题

我正在阅读《Go Bootcamp》,在第3章的第20页有一个例子我无法理解。在这个例子中,在printString(s)这一行中,s是一个fakeString类型的变量,但在switch语句中,进入了"Stringer"的case。我试图理解这是如何可能的。任何帮助将不胜感激。

代码如下:

package main
import "fmt"

type Stringer interface {
   String() string
}
type fakeString struct {
   content string
}
// 用于实现Stringer接口的函数
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")
}
英文:

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

得分: 0

因为fakeString是一种不同于string的类型,但它实现了Stringer接口。每个具有给定函数的类型都实现了该类型。fakeString包含String()函数,因此它也实现了Stringer接口。这是Go语言的一种基本原理。

检查内置库中的Reader接口,通常会以此作为示例。

英文:

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.

huangapple
  • 本文由 发表于 2017年3月31日 02:46:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/43126053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定