简体   繁体   中英

Multiple-value in single-value context

I'm currently trying out Go and am stuck with the aforementioned error message. Have a look at the interface, its implementation for float64 and the test.

Interface:

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
    }
}

Test:

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)
    }
}

The error occurs in the second line of the test function. I am aware that intersect returns two values: The interval and an error value. But since I am assigning both with got, _ := c.iv1.Intersect(c.iv2).(floatInterval) I thought I'm on the safe side. I also tried got, err := ... by the way. Is that due to the type conversion I'm doing with .(floatInterval) ?

It's because of the type assertion, which takes only a single value.

Do this instead:

gotInterval, _ := c.iv1.Intersect(c.iv2)
got := gotInterval.(floatInterval)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM