gpt4 book ai didi

Gotest - 不能使用 []int 文字(类型 []int)作为字段值中的类型参数

转载 作者:IT王子 更新时间:2023-10-29 02:26:53 24 4
gpt4 key购买 nike

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

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

我知道错误出在表参数上,但我不明白为什么 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)
}
})
}
}

不能使用 []int 文字(类型 []int)作为字段值中的类型参数

最佳答案

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

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

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

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

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

关于Gotest - 不能使用 []int 文字(类型 []int)作为字段值中的类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348462/

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