我正在为在结构(GO 语言)中启动 slice 而苦苦挣扎。这可能很容易,但我仍然无法解决。我遇到以下错误
./prog.go:11:1: syntax error: unexpected var, expecting field name or embedded type
./prog.go:25:2: no new variables on left side of :=
./prog.go:26:2: non-name g.s on left side of :=
我相信 s
应该被声明为结构的一部分,所以我想知道为什么我会收到那个错误。有人有什么建议吗?
package main
import "fmt"
type node struct {
value int
}
type graph struct {
nodes, edges int
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
}
最佳答案
你有一些错误:
-
当
g.s
已经由graph
类型定义。所以它不是一个“新变量”- 不能在类型声明中使用
var
- 您已经在
graphCreate
函数中声明了g
(作为返回类型) - 当你写一个文字结构时,you must pass none or all the field values or name them
- 您必须使用您声明的变量
g
是 graph
类型时,这是一个编译代码:
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
}
关于go - 结构中 slice 的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18827800/