du1108 2013-09-16 12:15
浏览 55
已采纳

切片在结构中的初始化

i am struggling with the initiation of a slice in a struct (GO-language). This may be easy, but still I can not solve it. I get

syntax error: unexpected var, expecting }
./test.go:28: no new variables on left side of :=
./test.go:29: non-name g.s on left side of := is the code;

I believe that s should be declared as part of the struct, so wonder why I get that error. Someone got some advice?

package main

import "fmt"

type node struct {
value int
}

type graph struct {
nodes , edges int
var s []int
} 

func main() {
g:= graphCreate()
}

func input(tname string)(number int){
fmt.Println("input a number of " + tname)
fmt.Scan(&number)
return 
}

func graphCreate()(g graph){
g:= graph{input("nodes"), input("edges")}
g.s := make([]int, 100)
return 
}
  • 写回答

1条回答 默认 最新

  • duanhuizhe6767 2013-09-16 12:22
    关注

    You have a few errors :

    • g.s is already defined by the type graph when g is of type graph. So it's not a "new variable"
    • you can't use var inside a type declaration
    • you have g already declared (as a return type) in your graphCreate function
    • when you write a literal struct, you must pass none or all the field values or name them
    • you must use the variables you declare

    here's a compiling code :

    package main
    
    import "fmt"
    
    type node struct {
        value int
    }
    
    type graph struct {
        nodes, edges int
        s            []int // <= there was var here
    }
    
    func main() {
        graphCreate() // <= g wasn't used
    }
    
    func input(tname string) (number int) {
        fmt.Println("input a number of " + tname)
        fmt.Scan(&number)
        return
    }
    
    func graphCreate() (g graph) { // <= g is declared here
        g = graph{nodes:input("nodes"), edges:input("edges")} // <= name the fields
        g.s = make([]int, 100) // <= g.s is already a known name
        return
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥15 小红薯封设备能解决的来
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'
  • ¥15 vue+element项目中多tag时,切换Tab时iframe套第三方html页面需要实现不刷新
  • ¥50 深度强化学习解决能源调度问题