簡體   English   中英

單值上下文中的多值

[英]Multiple-value in single-value context

我目前正在嘗試Go,並遇到了上述錯誤消息。 看看接口,它對float64的實現和測試。

接口:

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

錯誤發生在測試功能的第二行。 我知道相交會返回兩個值:時間間隔和錯誤值。 但是由於我同時got, _ := c.iv1.Intersect(c.iv2).(floatInterval)和分配got, _ := c.iv1.Intersect(c.iv2).(floatInterval)我以為我很安全。 順便說一句got, err := ...我也嘗試過got, err := ... 那是由於我正在使用.(floatInterval)進行類型轉換嗎?

這是因為類型斷言只需要一個值。

改為這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM