Gotest-不能在字段值中将[] int文字(类型[] int)用作args类型

时间:2019-03-26 01:05:09

标签: go

我正在尝试使用表测试来测试基本求和函数。这是函数:

func Sum(nums []int) int {
    sum := 0
    for _, n := range nums {
        sum += n
    }
    return sum
}

我确实知道错误与表args有关,但是我不明白为什么Golang不接受测试。一定要弄清楚。请参阅下面的测试和错误:

import (
    "testing"
)

func TestSum(t *testing.T) {

    type args struct {
        nums []int
    }
    tests := []struct {
        name string
        args args
        want int
    }{
        {"test", []int{3, 4}, 7},
        {"test", []int{3, 3}, 6},

    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := Sum(tt.args.nums); got != tt.want {
                t.Errorf("Sum() = %v, want %v", got, tt.want)
            }
        })
    }
}

cannot use []int literal (type []int) as type args in field value

1 个答案:

答案 0 :(得分:5)

这是因为您的匿名结构的第二个字段是args,而不是[]nums

您应该使用显式键入的args值对其进行初始化。

{"test", args{nums: []int{3, 4}}, 7},

或者,如果您更喜欢无字段结构文字:

{"test", args{[]int{3, 4}}, 7},
相关问题