在单值上下文中的多值

huangapple go评论76阅读模式
英文:

Multiple-value in single-value context

问题

我目前正在尝试使用Go语言,并且遇到了上述的错误信息。请查看接口、float64的实现以及测试部分。

接口:

package interval

import (
	"errors"
	"fmt"
	"math"
)

type Interval interface {
	Intersect(Y Interval) (Interval, error) // 当为空时,返回错误'nil'
}

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("空区间")
	} 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("期望值: [%f, %f] \t 实际值: [%f, %f]", c.intersectWant.a, c.intersectWant.b, got.a, got.b)
	}
}

错误发生在测试函数的第二行。我知道Intersect函数返回两个值:区间和一个错误值。但是由于我使用了got, _ := c.iv1.Intersect(c.iv2).(floatInterval)来同时赋值给两个变量,我以为这样是安全的。顺便说一下,我也尝试过got, err := ...。这是因为我使用了.(floatInterval)进行类型转换吗?

英文:

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

得分: 7

这是因为类型断言只接受单个值。

请改为以下方式:

gotInterval, _ := c.iv1.Intersect(c.iv2)
got := gotInterval.(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)

huangapple
  • 本文由 发表于 2015年4月14日 22:57:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/29630699.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定