go - 结构中 slice 的初始化

标签 go slice

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

最佳答案

你有一些错误:

    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
}

关于go - 结构中 slice 的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18827800/

相关文章:

戈朗 : Recursive data structures

Go 程序为每个 goroutine 创建 OS 线程,即使没有系统调用

go - 变量镜像其他

docker - 启动容器进程导致 “exec:\”转到\“: executable file not found in $PATH”:未知

go - 如何调试 ANTLR4 目标 Go 的监听器

json - 从 golang 中的 json 文件中读取 slice

arrays - 使用 [..] (slice) 方法引用数组时,Ruby 会创建副本吗?

Pandas 混合位置和标签索引而不链接

go - 在 Go 中交换变量值的最佳方式?

go - Go 没有真正的方法来缩小 slice 吗?这是一个问题吗?