我正在努力在结构(GO语言)中启动切片。这可能很容易,但我仍然无法解决。我得到了
语法错误:意外var,期待}
./test.go:28:左侧没有新变量:= ./test.go:29:左侧的非名称g.s:=是代码;
我相信s应该被声明为结构的一部分,所以我想知道为什么我会得到那个错误。有人得到了一些建议吗?
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
}
答案 0 :(得分:6)
您有一些错误:
g.s
类型为graph
时,g
已由graph
类型定义。所以它不是“新变量”var
g
函数graphCreate
(作为返回类型)
这是一个编译代码:
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
}