6

我正在努力在结构(GO 语言)中启动切片。这可能很容易,但我仍然无法解决。我得到以下错误

./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
}

4

1 回答 1

11

你有几个错误:

  • g.s已经由类型定义graphwheng是 type 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
}
于 2013-09-16T12:22:36.290 回答