为什么我的阵列没有增长?

Sam*_*are -2 arrays for-loop go slice

我正在尝试生成3 ||因子的数字 阵列中有5个.

这是我的代码的副本:

package main

import "fmt"

func main() {

    i := 0

    for i < 1000 {
        var nums []int

        if i%3 == 0 || i%5 == 0 {
            nums := append(nums, i)
            fmt.Println(nums)
        }

        i++

    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这并没有按计划通过在nums [0]上写入值来实现.这是我的终端输出的最后几个值.

[981]
[984]
[985]
[987]
[990]
[993]
[995]
[996]
[999]
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

UPDATE

还试过这个:

var nums []int // initialize the slice outside for loop
for i < 1000 {
    if i%3 == 0 || i%5 == 0 {
        nums = append(nums, i) // append to the slice outside loop not create a new one using short variable declaration
        fmt.Println(nums)
    }
    i++
}
Run Code Online (Sandbox Code Playgroud)

但得到了相同的结果

Him*_*shu 5

这是因为您正在创建[]int切片的新变量,而不是在条件之外附加到外部创建的切片.[]int在for循环外创建切片,如果是条件,则不使用short声明创建新变量.

package main

import (
    "fmt"
)

func main() {
    i := 0
    var nums []int
    for i < 1000 {
        if i%3 == 0 || i%5 == 0 {
            nums = append(nums, i)
        }
        i++
    }
    fmt.Println(nums)
    fmt.Println(len(nums), cap(nums)) // check for length and capacity of slice to know the size of slice after appending all data
}
Run Code Online (Sandbox Code Playgroud)

Go操场上的工作守则

  • @Data_Kid问题包含在我的答案中.每次循环执行代码时,您创建的切片都是新的.这是错误的,所以如果你打印出切片的len和容量,你肯定会知道.在增加切片尺寸时,请务必检查切片的长度和容量 (3认同)