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

为什么初始化后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.

图片转代码服务由CSDN问答提供 功能建议

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

下面是一段代码:

 包main 
 
import“ fmt” 
 
type Vec3 struct {
x float32 
y float32  
z float32 
} 
 
var一个[] 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)
} 
   
  
 

输出:

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

如果要查看,这也是一个repl.it链接。

感谢您的帮助。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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

相关推荐 更多相似问题