gpt4 book ai didi

string - 接口(interface)类型的 Golang String 方法

转载 作者:IT王子 更新时间:2023-10-29 01:05:33 25 4
gpt4 key购买 nike

我正在解决这本书的问题 The Go Programming Language ,在练习 7.13 中,要求将 String 方法添加到接口(interface)中。

是否可以将 String() 方法添加到接口(interface)?因为直到运行时才知道数据类型。

最佳答案

将方法添加到接口(interface)只是意味着将该方法包含在接口(interface)类型定义的方法集中。

例如这是一个接口(interface):

type Fooer interface {
Foo()
}

它有一个方法:Foo()。要将 String() 方法添加到此接口(interface):

type Fooer interface {
Foo()
String() string
}

完成。我们已将 String() 方法添加到此接口(interface)。

这会导致如果一个具体类型想要实现此 Fooer 接口(interface),以前只需要一个 Foo() 方法就足够了。现在它还必须有一个 String() 方法。

另请注意,在 Go 中实现接口(interface)是隐式的。 没有意图声明。如果一个类型具有接口(interface)的所有方法,则它隐式满足接口(interface)。

具体类型可能有也可能没有 String() 方法,独立于我们的 Fooer 接口(interface)。具体类型甚至可能不知道我们的 Fooer 接口(interface),也不需要。

下面是实现此 Fooer 接口(interface)的具体类型:

type fooerImpl int

func (f fooerImpl) Foo() {
fmt.Printf("Foo() called, I'm %d\n", int(f))
}

func (f fooerImpl) String() string {
return fmt.Sprintf("Foo[%d]", int(f))
}

测试它:

var f Fooer = fooerImpl(3)
f.Foo()
fmt.Println(f.String())
fmt.Println(f)

输出(在 Go Playground 上尝试):

Foo() called, I'm 3
Foo[3]
Foo[3]

向接口(interface)添加方法的结果

如果您任意向接口(interface)添加新方法,可能会导致某些先前实现该接口(interface)的现有具体类型不再实现它(由于缺少新添加的方法)。

如果这些现有的具体类型被用作接口(interface)的实例,它们将导致编译时错误,并且在您添加缺少的新方法之前将无法工作。例如,如果我们从上面的示例中删除 fooerImpl.String() 方法,则代码 var f Fooer = fooerImpl(3) 会导致编译时错误:

cannot use fooerImpl(3) (type fooerImpl) as type Fooer in assignment:
fooerImpl does not implement Fooer (missing String method)

如果现有的具体类型没有直接用作接口(interface)的实例,但是例如它们被包装在空接口(interface) interface{}type assertion 中传递用于提取接口(interface)的值,那些类型断言将不再成立。类型断言的“简单”形式 x.(T) 将导致运行时 panic ,特殊形式 v, ok := x.(T) 将返回 nilfalse

例如使用上面的 fooerImpl 类型而不使用 String() 方法:

var f0 interface{} = fooerImpl(3)
f := f0.(Fooer)

导致运行时 panic :

panic: interface conversion: main.fooerImpl is not main.Fooer: missing method String

并使用特殊形式的类型转换:

if f, ok := f0.(Fooer); ok {
f.Foo()
} else {
fmt.Println("Not instance of Fooer!", f)
}

结果:

Not instance of Fooer! <nil>

如果现有的具体类型已经有一个您刚刚添加到接口(interface)的方法并且它具有相同的签名(相同的参数和返回类型),那么这很酷,具体类型将“继续”实现新界面也一​​样。如果签名不匹配(例如,现有方法具有不同的返回类型),那么它将不满足接口(interface),这与没有同名方法是一样的。

关于string - 接口(interface)类型的 Golang String 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38393325/

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