【问题标题】:Gotest - cannot use []int literal (type []int) as type args in field valueGotest - 不能使用 []int 文字(类型 []int)作为字段值中的类型 args
【发布时间】:2019-03-26 09:30:30
【问题描述】:

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

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

【问题讨论】:

    标签: go


    【解决方案1】:

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

    您应该将其初始化为显式键入的 args 值。

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

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

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

    【讨论】:

    • @zerkms 没问题!如果您有时间,我还有其他需要审核的编辑建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 2019-08-14
    相关资源
    最近更新 更多