gpt4 book ai didi

go - 单值上下文中的多值

转载 作者:IT王子 更新时间:2023-10-29 01:24:54 25 4
gpt4 key购买 nike

我目前正在试用 Go,但遇到了上述错误消息。查看接口(interface)、其 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
}
}

测试:

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

错误出现在测试函数的第二行。我知道 intersect 返回两个值:间隔和错误值。但是由于我用 got, _ := c.iv1.Intersect(c.iv2).(floatInterval) 分配两者,我认为我是安全的。顺便说一下,我也尝试了 got, err := ... 。这是因为我正在使用 .(floatInterval) 进行类型转换吗?

最佳答案

这是因为类型断言,它只接受一个值。

改为这样做:

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

关于go - 单值上下文中的多值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29630699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com