如何从函数访问结构的实例字段?
How to access struct's instance fields from a function?
假设我有一个 Graph
结构,如下所示:
type Graph struct {
nodes []int
adjList map[int][]int
}
// some methods on the struct
// constructor
func New() *Graph {
g := new(Graph)
g.adjList = make(map[int][]int)
return g
}
现在,我创建了该结构的一个新实例,其中:aGraph := New()
。
如何访问 Graph
结构 (aGraph
) 的这个特定实例的字段?
换句话说,我如何访问 aGraph
版本的 nodes
数组(例如,从另一个顶级函数中)?
非常感谢任何帮助!
这是一个例子:
package main
import (
"fmt"
)
// example struct
type Graph struct {
nodes []int
adjList map[int][]int
}
func New() *Graph {
g := new(Graph)
g.adjList = make(map[int][]int)
return g
}
func main() {
aGraph := New()
aGraph.nodes = []int {1,2,3}
aGraph.adjList[0] = []int{1990,1991,1992}
aGraph.adjList[1] = []int{1890,1891,1892}
aGraph.adjList[2] = []int{1890,1891,1892}
fmt.Println(aGraph)
}
输出:&{[1 2 3 4 5] 映射[0:[1990 1991 1992] 1:[1890 1891 1892] 2:[1790 1791 1792]]}
假设我有一个 Graph
结构,如下所示:
type Graph struct {
nodes []int
adjList map[int][]int
}
// some methods on the struct
// constructor
func New() *Graph {
g := new(Graph)
g.adjList = make(map[int][]int)
return g
}
现在,我创建了该结构的一个新实例,其中:aGraph := New()
。
如何访问 Graph
结构 (aGraph
) 的这个特定实例的字段?
换句话说,我如何访问 aGraph
版本的 nodes
数组(例如,从另一个顶级函数中)?
非常感谢任何帮助!
这是一个例子:
package main
import (
"fmt"
)
// example struct
type Graph struct {
nodes []int
adjList map[int][]int
}
func New() *Graph {
g := new(Graph)
g.adjList = make(map[int][]int)
return g
}
func main() {
aGraph := New()
aGraph.nodes = []int {1,2,3}
aGraph.adjList[0] = []int{1990,1991,1992}
aGraph.adjList[1] = []int{1890,1891,1892}
aGraph.adjList[2] = []int{1890,1891,1892}
fmt.Println(aGraph)
}
输出:&{[1 2 3 4 5] 映射[0:[1990 1991 1992] 1:[1890 1891 1892] 2:[1790 1791 1792]]}