【发布时间】:2020-10-22 12:21:11
【问题描述】:
在下面的代码中,我们在第 5,6,7 行使用了type definition 语法:
package math
// Constructors and Selectors
type RationalNumber []int // Line 5
type Numerator int
type Denominator int
// Constructor - Construct a rational number x that represents n/d
func NewRationalNumber(n int, d int) RationalNumber {
g := gcd(n, d)
return []int{n / g, d / g} // Line 12
}
//Selector
func numer(x RationalNumber) Numerator {
return x[0] // Line 17
}
//Selector
func denom(x RationalNumber) Denominator {
return x[1]
}
return []int{n / g, d / g}不报错,
在哪里,
return x[0] & return x[1] 给出错误:
math/numbers.go:17:10: cannot use x[0] (type int) as type Numerator in return argument
math/numbers.go:22:10: cannot use x[1] (type int) as type Denominator in return argument
对于第 5、6、7 行中给定的 3 个类型定义,我理解第 17 行错误背后的原因,但是,
-
为什么第 12 行没有给出类似的错误?
-
如何解决这个错误?不改变函数的签名?
【问题讨论】: