dqmfo84644 2017-02-09 14:01
浏览 286
已采纳

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

My question here is why the slice is empty in another func when the slice is global to the file?

Here's a piece of code:

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
", a)
  doSomethingWithA();
}

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

Output:

[{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 is a repl.it link too, if you want to take a look.

Thanks for your kind help.

  • 写回答

2条回答 默认 最新

  • dszm02606009 2017-02-09 14:21
    关注

    You have redefined it here:

    a := make([]Vec3, 0)
    

    To use the same variable you should assign a value with = but not declare a new variable with :=

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器