gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:42:57 26 4
gpt4 key购买 nike

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

这是一段代码:

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.it 链接。

感谢您的帮助。

最佳答案

你在这里重新定义了它:

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.

关于go - 为什么golang slice初始化后为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42138710/

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