简体   繁体   English

单值上下文中的多值

[英]Multiple-value in single-value context

I'm currently trying out Go and am stuck with the aforementioned error message. 我目前正在尝试Go,并遇到了上述错误消息。 Have a look at the interface, its implementation for float64 and the test. 看看接口,它对float64的实现和测试。

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. 但是由于我同时got, _ := c.iv1.Intersect(c.iv2).(floatInterval)和分配got, _ := c.iv1.Intersect(c.iv2).(floatInterval)我以为我很安全。 I also tried got, err := ... by the way. 顺便说一句got, err := ...我也尝试过got, err := ... Is that due to the type conversion I'm doing with .(floatInterval) ? 那是由于我正在使用.(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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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