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条)

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan