【问题标题】:init of slice in struct结构中切片的初始化
【发布时间】:2013-09-16 12:15:59
【问题描述】:

我正在努力在结构(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
}

【问题讨论】:

  • 您提到的编译器错误清楚地说明了错误是什么。您应该将这两个:=s 替换为=

标签: go slice


【解决方案1】:

你有一些错误:

  • ggraph 类型时,g.s 已经由graph 类型定义。所以它不是一个“新变量”
  • 你不能在类型声明中使用var
  • 您已经在 graphCreate 函数中声明了 g(作为返回类型)
  • 当你写一个文字结构时,you must pass none or all the field values or name them
  • 你必须使用你声明的变量

这是一个编译代码:

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
}

【讨论】:

  • 意外的 var,期待 } 怎么样?
  • 谢谢。我需要去,所以这些答案对我非常有用:)
  • 您可能不需要g.s = make([]int, 100) 行。 nil 切片(零值)用作空切片,您可以 append 对其进行处理。这样做的唯一原因是,如果您确定预先知道最终大小并关心最大效率,或者您希望随机而不是按顺序填充切片。
猜你喜欢
  • 1970-01-01
  • 2017-07-23
  • 2018-01-20
  • 1970-01-01
  • 2021-02-19
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多