在结构中初始化切片

问题描述 投票:6回答:1

我正在努力解决结构(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
var 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 
}
go slice
1个回答
10
投票

你有几个错误。

这是一个编译代码。

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
}
© www.soinside.com 2019 - 2024. All rights reserved.