[英]Multiple-value in single-value context
我目前正在尝试Go,并遇到了上述错误消息。 看看接口,它对float64的实现和测试。
接口:
package interval
import (
"errors"
"fmt"
"math"
)
type Interval interface {
Intersect(Y Interval) (Interval, error) // Intersection of X and Y, error 'nil' when empty
}
type floatInterval struct {
a, b float64
}
func (fi floatInterval) Intersect(Y Interval) (Interval, error) {
tmp := Y.(floatInterval)
a_new, b_new := math.Max(fi.a, tmp.a), math.Min(fi.b, tmp.b)
result := floatInterval{a_new, b_new}
if result.Length() == 0 {
return result, errors.New("Empty interval")
} else {
return result, nil
}
}
测试:
func intersect_test(t *testing.T, c testTuple) {
got, _ := c.iv1.Intersect(c.iv2).(floatInterval)
if (c.intersectWant.a != got.a) || (c.intersectWant.b != got.b) {
t.Errorf("Expected: [%f, %f] \t Got: [%f, %f]", c.intersectWant.a, c.intersectWant.b, got.a, got.b)
}
}
错误发生在测试功能的第二行。 我知道相交会返回两个值:时间间隔和错误值。 但是由于我同时got, _ := c.iv1.Intersect(c.iv2).(floatInterval)
和分配got, _ := c.iv1.Intersect(c.iv2).(floatInterval)
我以为我很安全。 顺便说一句got, err := ...
我也尝试过got, err := ...
那是由于我正在使用.(floatInterval)
进行类型转换吗?
这是因为类型断言只需要一个值。
改为这样做:
gotInterval, _ := c.iv1.Intersect(c.iv2)
got := gotInterval.(floatInterval)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.