英文:
init of slice in struct
问题
我正在努力解决在结构体中初始化切片的问题(GO语言)。这可能很简单,但我仍然无法解决它。我得到以下错误:
./prog.go:11:1: 语法错误:意外的 var,期望字段名或嵌入类型
./prog.go:25:2: := 左侧没有新变量
./prog.go:26:2: := 左侧的非名称 g.s
我相信 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
}
英文:
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 below error
./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 :=
I believe that s
should be declared as part of the struct, so I 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
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
得分: 12
你有几个错误:
- 当
g
的类型为graph
时,g.s
已经被类型graph
定义,所以它不是一个"新变量" - 你不能在类型声明中使用
var
- 你已经在
graphCreate
函数中声明了g
(作为返回类型) - 当你写一个字面结构时,你必须传递所有字段值或命名它们
- 你必须使用你声明的变量
这是一个可以编译的代码:
package main
import "fmt"
type node struct {
value int
}
type graph struct {
nodes, edges int
s []int // <= 这里原本有一个var
}
func main() {
graphCreate() // <= 没有使用g
}
func input(tname string) (number int) {
fmt.Println("input a number of " + tname)
fmt.Scan(&number)
return
}
func graphCreate() (g graph) { // <= 这里声明了g
g = graph{nodes: input("nodes"), edges: input("edges")} // <= 命名字段
g.s = make([]int, 100) // <= g.s已经是一个已知的名称
return
}
英文:
You have a few errors :
g.s
is already defined by the typegraph
wheng
is of typegraph
. 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 yourgraphCreate
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论