dongli8862
2016-04-02 22:36
浏览 355
已采纳

去:在结构体中声明一个切片?

I have the following code:

type room struct {
    width float32
    length float32
}
type house struct{
    s := make([]string, 3)
    name string
    roomSzSlice := make([]room, 3)
} 

func main() {


}

And when i try to build and run it i get the following errors:

c:\go\src\test\main.go:10: syntax error: unexpected :=
c:\go\src\test\main.go:11: non-declaration statement outside function body
c:\go\src\test\main.go:12: non-declaration statement outside function body
c:\go\src\test\main.go:13: syntax error: unexpected }

What did i do wrong?

Thanks!

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

我有以下代码:

  type room struct {  
宽度float32 
长度float32 
} 
键入房屋结构{
s:= make([] string,3)
名称字符串
 roomSzSlice:= make([] room,3)
} 
  
func main(){
 
 
} 
   
 
 

当我尝试构建并运行它时,出现以下错误: \ n

  c:\ go \ src \ test \ main.go:10:语法错误:意外:= 
c:\ go \ src \ test \ main.go:11:非声明语句 外部函数主体
c:\ go \ src \ test \ main.go:12:非声明语句外部函数主体
c:\ go \ src \ test \ main.go:13:语法错误:意外} 
 <  / code>  
 
 

我做错了什么?

谢谢!

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

2条回答 默认 最新

  • douping5226 2016-04-02 23:20
    已采纳

    First off you cannot assign/initialize inside the struct. The := operator declares and assigns. You can however, achieve the same result simply.

    Here is a simple, trivial example that would do roughly what you're trying:

    type house struct {
        s []string
    }
    
    func main() {
        h := house{}
        a := make([]string, 3)
        h.s = a
    }
    

    I've never written one that way, but if it servers your purpose... it compiles anyway.

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题