为什么golang slice初始化后为空?

Why golang slice is empty after initialization?

我的问题是,当切片对文件是全局的时,为什么另一个函数中的切片是空的?

这是一段代码:

package main

import "fmt"

type Vec3 struct {
    x float32
    y float32
    z float32
}

var a []Vec3

func main() {
  a := make([]Vec3, 0)

  a = append(a, Vec3{2.0, 3.0, 4.0})
  a = append(a, Vec3{3.4, 5.6, 5.4})
  a = append(a, Vec3{6.7, 4.5, 7.8})

  fmt.Printf("%+v\n", a)
  doSomethingWithA();
}

func doSomethingWithA() {
  fmt.Printf("%+v\n", a)
}

输出:

[{x:2 y:3 z:4} {x:3.4 y:5.6 z:5.4} {x:6.7 y:4.5 z:7.8}]
[]

This也是repl.itlink,如果你想看一看。

感谢您的帮助。

你重新声明了一个,所以实际上你没有初始化全局变量,试试:

a = make([]Vec3, 0)

您在这里重新定义了它:

a := make([]Vec3, 0)

要使用相同的变量,您应该使用 = 赋值,但不要使用 :=

声明新变量
a = make([]Vec3, 0)

Short variable declarations

Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.