Go语言 按范围切片中的筛选器编号有问题

ulydmbyx  于 2023-03-06  发布在  Go
关注(0)|答案(1)|浏览(126)

我遇到了一个关于范围编号的问题,我必须过滤并输入到evennumbers数组中,但是我得到了编译错误

Make me compile!
//
// I AM NOT DONE
package main_test
 
import (
    "reflect"
    "testing"
)
 
func TestFilterEvenNumbers(t *testing.T) {
    numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
 
    evenNumbers := []int{} // use range to filter even numbers
 
    for _, evenNumbers := range numbers {
        if numbers % 2 {
            evenNumbers = append(numbers)
        }

    }
 
    if !reflect.DeepEqual(evenNumbers, []int{2, 4, 6, 8, 10}) {
        t.Errorf("evenNumbers does not contain all the required even 
        numbers, got %v", evenNumbers)
    }
}

检查以下输出

# command-line-arguments_test [command-line-arguments.test]
exercises/range/range3/main_test.go:18:22: cannot convert 2 (untyped int constant) to []int
exercises/range/range3/main_test.go:19:27: cannot use append(numbers) (value of type []int) as type int in assignment
FAIL    command-line-arguments [build failed]
FAIL
jm81lzqq

jm81lzqq1#

这段代码是完全错误的,你使用的是数组而不是数组元素,并且没有正确检查% condition。循环应该是:

for _, number := range numbers {
    if number%2 == 0 {
        evenNumbers = append(evenNumbers, number)
    }
}

相关问题