dpbe81245 2015-04-14 14:57
浏览 30
已采纳

单值上下文中的多值

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

  • 写回答

1条回答 默认 最新

  • douzhuiqiu4923 2015-04-14 14:59
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器