go - 在 Golang 中,在结构内部使用接口是什么意思?
问题描述
新来这里。我遇到了一些与 DynamoDB 相关的代码:
type Dynamo interface {
DescribeTableWithContext(
aws.Context,
*dynamodb.DescribeTableInput,
...request.Option,
) (*dynamodb.DescribeTableOutput, error)
}
type my_struct struct {
Dynamo
}
我是否正确假设my_struct
“实现”了 Dynamo 接口,现在可以使用该DescribeTableWithContext
方法?
解决方案
我假设 my_struct “实现” Dynamo 接口是否正确
不完全是。无论您my_struct
为Dynamo
嵌入初始化的结构将是实现接口的东西。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 方法了吗?
是的,假设您在初始化期间提供了接口实现。
编辑:添加了对实现接口与仅仅满足它的含义的解释。
推荐阅读
- python - Python to SQL Server insert query to varbinary(max) column
- algorithm - 4 节点红黑树应该是什么样子
- python - Broken xx axis and adjustment of the log-normal distribution in a histogram
- sendgrid - How does Sendgrid's automated security works?
- python - How to get the file name of a PIL image?
- installation - Unable to load dynamic library 'blackfire'
- twitter - Twitter OAuth 1.0 "215 Bad Authentication Data" error when requesting token
- python - Class weights for multi-output classification
- javascript - Sequelize Create/Post with M:N
- camunda - Camunda A/B Testing