gpt4 book ai didi

Golang : Where is an Interface method called?

转载 作者:IT老高 更新时间:2023-10-28 13:10:15 25 4
gpt4 key购买 nike

我不明白什么时候调用了接口(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.Formatterfmt.GoStringererror,最后检查 fmt.Stringer

关于Golang : Where is an Interface method called?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34229699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com