Why does Go not have variant types?
为什么 Go 没有可变类型?
Variant types, also known as algebraic types, provide a way to specify that a value might take one of a set of other types, but only those types. A common example in systems programming would specify that an error is, say, a network error, a security error or an application error and allow the caller to discriminate the source of the problem by examining the type of the error. Another example is a syntax tree in which each node can be a different type: declaration, statement, assignment and so on.
可变类型(也称为代数类型)提供了一种方法来接纳一组其他类型中的一种,但只能采用这些类型。系统编程中的一个常见示例会指定错误是网络错误、安全错误或应用程序错误,并允许调用者通过检查错误类型来区分问题的根源。另一个例子是语法树,其中每个节点可以是不同的类型:声明、语句、赋值等等。
algebraic
adj. 代数的,关于代数学的;
discriminate
v. 区分,辨别;歧视,偏袒;
We considered adding variant types to Go, but after discussion decided to leave them out because they overlap in confusing ways with interfaces. What would happen if the elements of a variant type were themselves interfaces?
我们考虑过向 Go 添加可变类型,但经过讨论后决定将它们排除在外,因为它与接口的功能更以令人困惑的方式重叠。如果可变类型的元素本身就是接口,会发生什么?
Also, some of what variant types address is already covered by the language. The error example is easy to express using an interface value to hold the error and a type switch to discriminate cases. The syntax tree example is also doable, although not as elegantly.
此外,可变类型所解决的一些问题已经被语言本身涵盖了。错误示例很容易表示,使用接口值来保持错误和类型开关来区分情况。语法树示例也是可行的,尽管不是那么优雅。
doable
adj. 可做的,可行的;
Why does Go not have covariant result types?
为什么 Go 没有协变结果类型?
Covariant result types would mean that an interface like
协变结果类型意味着像这样的接口
type Copyable interface {
Copy() interface{}
}
would be satisfied by the method
该方法将满足
func (v Value) Copy() Value
because Value implements the empty interface. In Go method types must match exactly, so Value does not implement Copyable. Go separates the notion of what a type does—its methods—from the type's implementation. If two methods return different types, they are not doing the same thing. Programmers who want covariant result types are often trying to express a type hierarchy through interfaces. In Go it's more natural to have a clean separation between interface and implementation.
因为Value实现了空接口。在 Go 中方法类型必须完全匹配,因此Value没有实现Copyable接口. Go 将类型的功能(其方法)的概念与类型的实现分开。如果两个方法返回不同的类型,则它们没有做相同的事情。想要协变结果类型的程序员通常尝试通过接口来表达类型层次结构。在 Go 中,接口和实现之间的清晰分离更为自然。
函数的协变返回值类型指的是子类中的成员函数的返回值类型不必严格等同与该函数所重写的父类中的函数的返回值类型,而可以是更 “狭窄” 的类型。C++/Java等面向对象编程语言均支持协变返回值类型。