英文:
Implementation of an interface which contains a struct
问题
我对Go语言中的类型集有些困惑。在Go 1.18之后,Go支持在接口中嵌入结构体。例如,下面的代码是合法的Go代码:
type ABCInterface interface {
ABC
}
type ABC struct {
A, B, C int
}
我的问题是,如何实例化一个满足ABCInterface接口的对象?
我尝试创建ABC的实例,但它不是ABCInterface类型的。
我还定义了一个新的结构体:
type ABCImpl struct {
ABC
}
但这也不是ABCInterface的实现。
英文:
I am bit confused about how the typesets in go work. Post Go 1.18, go supports embedding structs inside an interface. For instance, this is perfectly valid go code :
type ABCInterface interface {
ABC
}
type ABC struct {
A, B, C int
}
My question is how do I instantiate an object which satisfies the ABCInterface?
I tried creating instance of ABC but that is not of type ABCInterface.
I also defined a new struct
type ABCImpl struct {
ABC
}
but this is not an implementation of ABCInterface as well.
答案1
得分: 2
在Go语言中,接口是一组方法签名,用于定义结构体(或类型)必须遵循的行为。当一个结构体实现了接口指定的所有方法时,就称为满足或实现了该接口。
在你的情况下,假设你想要一个实现Sum
方法的接口。要实现该接口,你可以按照以下方式添加监听器:
package main
import "log"
// ABCInterface 提供了一个包含 Sum 方法的类型的蓝图。
type ABCInterface interface {
Sum() int
}
// ABC 是表示 A、B 和 C 值的类型。
type ABC struct {
A, B, C int
}
// ABCImpl 是继承 ABC 字段并实现 ABCInterface 的类型。
type ABCImpl struct {
ABC
}
// Sum 计算 A、B 和 C 的和并返回结果。
func (a ABCImpl) Sum() int {
return a.C + a.A + a.B
}
func main() {
// 创建 ABCImpl 的实例。
trialValue := ABCImpl{
ABC: ABC{
A: 1,
B: 2,
C: 3,
},
}
// 调用 trialValue 实例的 Sum 方法并打印结果。
log.Println(trialValue.Sum())
}
你也可以省略 ABC
结构体,直接使用以下方式定义 ABCImpl
:
type ABCImpl struct {
A, B, C int
}
希望对你有帮助!
英文:
In Go, an interface is a set of method signatures that define the behavior that a struct (or type) must adhere to. When a struct implements all the methods specified by an interface, it is said to satisfy or implement that interface.
In your case, let's consider that you want an interface that implements a Sum
method. To implement the interface, you'll add the listener as follows:
package main
import "log"
// ABCInterface provides a blueprint for types that include the Sum method.
type ABCInterface interface {
Sum() int
}
// ABC is a type that represents values of A, B, and C.
type ABC struct {
A, B, C int
}
// ABCImpl is a type that inherits fields from ABC and implements ABCInterface.
type ABCImpl struct {
ABC
}
//You could eliminate the `ABC` struct and simply use
type ABCImpl struct {
A,B,C int
}
// Sum calculates the sum of A, B, and C and returns the result.
func (a ABCImpl) Sum() int {
return a.C + a.A + a.B
}
func main() {
// Create an instance of ABCImpl.
trialValue := ABCImpl{
ABC: ABC{
A: 1,
B: 2,
C: 3,
},
}
// Call the Sum method on the trialValue instance and print the result.
log.Println(trialValue.Sum())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论