单值上下文中的多值

时间:2015-04-14 14:57:23

标签: go

我目前正在尝试使用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)
    }
}

错误发生在测试功能的第二行。我知道intersect返回两个值:interval和error值。但是因为我正在分配两个got, _ := c.iv1.Intersect(c.iv2).(floatInterval)我认为我是安全的。顺便说一句,我也试过got, err := ...。这是由于我使用.(floatInterval)进行的类型转换吗?

1 个答案:

答案 0 :(得分:6)

这是因为类型断言只占用一个值。

请改为:

gotInterval, _ := c.iv1.Intersect(c.iv2)
got := gotInterval.(floatInterval)
相关问题