Haskell 的 TypeClasses 和 Go 的 Interfaces 有什么异同?两种方法的相对优缺点是什么?
最佳答案
看起来像 only in superficial ways是 Go 接口(interface),类似于 Haskell 中的单参数类型类(构造函数类)。
- 方法与接口(interface)类型相关联
- 对象(特定类型)可能具有该接口(interface)的实现
我不清楚 Go 是否以任何方式通过接口(interface)支持有界多态性,这是类型类的主要目的。也就是说,在Haskell中,接口(interface)方法可以用在不同的类型上,
class I a where
put :: a -> IO ()
get :: IO a
instance I Int where
...
instance I Double where
....
所以我的问题是 Go 是否支持类型多态。如果不是,它们根本不像类型类。而且它们没有可比性。
Haskell 的类型类允许通过“泛型”强大的代码重用——更高种类的多态——cross-language support for such forms of generic program is this paper 的一个很好的引用。 .
通过类型类的特殊或有界多态是well described here .这是 Haskell 中类型类的主要目的,并且没有通过 Go 接口(interface)解决,这意味着它们根本不是非常相似。接口(interface)严格来说没有那么强大 - 一种零阶类型类。
关于programming-languages - Haskell 的类型类和 Go 的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2982012/