首页 > 解决方案 > 在 Golang 中,在结构内部使用接口是什么意思?

问题描述

新来这里。我遇到了一些与 DynamoDB 相关的代码:

type Dynamo interface {
    DescribeTableWithContext(
        aws.Context,
        *dynamodb.DescribeTableInput,
        ...request.Option,
    ) (*dynamodb.DescribeTableOutput, error)
}

type my_struct struct {
    Dynamo
}

我是否正确假设my_struct“实现”了 Dynamo 接口,现在可以使用该DescribeTableWithContext方法?

标签: gointerface

解决方案


我假设 my_struct “实现” Dynamo 接口是否正确

不完全是。无论您my_structDynamo嵌入初始化的结构将是实现接口的东西。my_struct但是会在编译时满足接口。Dynamo正如@mkopriva 指出的那样,在运行时,这确实需要嵌入式接口的具体实现。因此,如果您要执行以下操作:

package main

import "fmt"

type Adder interface {
    func Add(a, b int) int
}

type Embed struct {
    Adder
}

func PrintAdd(a Adder, first, second int) {
    fmt.Println(a.Add(first, second))
}

func main() {
    e := Embed{}
    PrintAdd(e, 1, 2)
}

此代码将编译,但在运行时,调用PrintAdd将失败,因为尚未设置嵌入式接口实现。

如果将上面的 main 替换为:

type adder struct {}

func (a adder) Add(first, second int) int {
     return first + second
}

func main() {
    e := Embed{adder{}}
    PrintAdd(e, 1, 2)
}

事情将按预期进行。

...现在可以使用 DescribeTableWithContext 方法了吗?

是的,假设您在初始化期间提供了接口实现。

编辑:添加了对实现接口与仅仅满足它的含义的解释。


推荐阅读