Go sort.Interface作为参数
但它抱怨说Go sort.Interface作为参数,go,Go,但它抱怨说 func TestIsPalindrome(t *testing.T) { tests := []struct { a sort.Interface r bool }{ {a: []int{1, 3, 1}, r: true}, {a: "helloolled", r: true}, {a: "The Go Programming Language", r: false}, }
func TestIsPalindrome(t *testing.T) {
tests := []struct {
a sort.Interface
r bool
}{
{a: []int{1, 3, 1}, r: true},
{a: "helloolled", r: true},
{a: "The Go Programming Language", r: false},
}
for row, test := range tests {
assert.Equal(t, test.r, IsPalindrome(test.a), "row: %d\n", row)
}
}
我认为[]int是一个切片,“helloolled”是字符串,两者都应该有Len方法
我的代码有什么问题?“两者都应该有Len方法”-可能是这样。那么
越少越好
?(和Swap
,此处不使用)slice和string都没有Len方法。这些是可以传递到len
函数中的内置类型,但这并不意味着它们具有len
方法或实现len
方法。所有类型都没有任何方法,也没有未命名(例如,[]string
)类型有任何方法,因此它们只能实现空接口。@mkopriva非常感谢您的帮助,我想我作为新手还有很长的路要走。您可以使用“reflect”库为类型添加筛选器
func TestIsPalindrome(t *testing.T) {
tests := []struct {
a sort.Interface
r bool
}{
{a: []int{1, 3, 1}, r: true},
{a: "helloolled", r: true},
{a: "The Go Programming Language", r: false},
}
for row, test := range tests {
assert.Equal(t, test.r, IsPalindrome(test.a), "row: %d\n", row)
}
}
cannot use []int literal (type []int) as type sort.Interface in field value:
[]int does not implement sort.Interface (missing Len method)
cannot use "helloolled" (type string) as type sort.Interface in field value:
string does not implement sort.Interface (missing Len method)
....