作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我不明白什么时候调用了接口(interface)方法。我正在查看 Go Tour 中的以下示例:
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p Person) String() string {
return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
}
func main() {
a := Person{"Arthur Dent", 42}
z := Person{"Zaphod Beeblebrox", 9001}
fmt.Println(a, z)
}
问题:
我了解 func (p Person)
接收 String()
方法并返回我想要显示的 string
。但是 main()
方法中的 fmt.Println
必须在某个时候调用 String()
对吧?
我在godoc中查看了fmt
的来源,但还是不明白!
另一个例子:
如果我添加自己的接口(interface),假设 Stringer2
使用名为 String2()
的方法,然后创建一个 func (p Person) String2() { ....}
。String()
是如何被 fmt.Println
执行的,而 String2()
不是?
最佳答案
该值作为 interface{}
传递给 Println
,并通过 "type assertion" 检查它是否满足 fmt.Stringer
接口(interface)通常采用 "type switch" 的形式。
func IsStringer(i interface{}) {
switch s := i.(type) {
case fmt.Stringer:
fmt.Println("Person a has a String() method")
fmt.Println(s.String())
default:
fmt.Println("not a stringer")
}
// OR for a single type
if s, ok := i.(fmt.Stringer); ok {
fmt.Println("Person a has a String() method")
fmt.Println(s.String())
}
}
但是,从 fmt
包进行打印时,可能会优先使用其他方法。首先检查 fmt.Formatter
、fmt.GoStringer
、error
,最后检查 fmt.Stringer
。
关于Golang : Where is an Interface method called?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34229699/
我是一名优秀的程序员,十分优秀!