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 python结合Matlab仿真忆阻器
  • ¥35 有人会注册whatsaop协议号吗?
  • ¥15 lead dbs 无法导入影像数据
  • ¥15 多目标MPA算法优化编程实现
  • ¥15 反激PWM控制芯片调研
  • ¥15 Python for loop减少运行时间
  • ¥15 fluent模拟物质浓度udf
  • ¥15 Collection contains no element matching the predicate
  • ¥20 冻品电商平台的搜索是怎么实现的
  • ¥15 如何搞一个可以控制、显示马达频率