单值上下文中的多值

Den*_*r21 2 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
    }
}
Run Code Online (Sandbox Code Playgroud)

测试:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

错误发生在测试功能的第二行.我知道intersect返回两个值:interval和error值.但既然我正在分配这两个,got, _ := c.iv1.Intersect(c.iv2).(floatInterval)我以为我是安全的.我也试过got, err := ...了.这是由于我正在做的类型转换.(floatInterval)

rig*_*old 6

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

改为:

gotInterval, _ := c.iv1.Intersect(c.iv2)
got := gotInterval.(floatInterval)
Run Code Online (Sandbox Code Playgroud)