gpt4 book ai didi

Golang 推断接口(interface)

转载 作者:IT王子 更新时间:2023-10-29 00:50:00 26 4
gpt4 key购买 nike

这里只是一个简单的语言设计相关问题。在像 Swift 这样的语言中,为了使结构/类符合协议(protocol)/接口(interface),需要明确声明它

struct Dog: Animal {
// implementation of Animal protocols here
}

但为什么在 Go 中,没有明确的方法来显示结构符合哪些接口(interface)?

这不是说不清楚还是另有原因?

最佳答案

这允许进化为甚至为遗留类型(从未明确声明尊重所述接口(interface))提供接口(interface)

如果这些类型已经提供了正确的方法(即与您的接口(interface)指定的 API 相同的 API),它们将满足该接口(interface)。

这允许在那些遗留类型(不知道您的接口(interface)存在)和您的程序之间保持低耦合,您的程序接受该接口(interface)的实例。

参见“What are some examples of Go interfaces?

Go's interfaces aren't a variant on Java or C# interfaces, they're much more.
They are a key to large-scale programming and adaptable, evolutionary design.

"It's the fact that I don't have to spend time up front designing some sort of type hierarchy and then rearranging it two or three times before I finish.
It's not even the fact that it's easy to do it right -
it's the fact that I just don't have to worry about it and can get on with the actual algorithm."

这些引述来自 2012 article , 也来自 this thread ,您可以在其中阅读 Rob Pike's comment :

"It's always bothered me in OO languages that we can make Circle, Square, etc. subclasses of Shape (say), but that's the one design decision we get to make.
What if we want to align those things along other axes (so to speak), like topological genus or plant genus, if you're a landscaper? You might lose your way or dig yourself into a hole with multiple inheritance."

关于Golang 推断接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41437046/

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