英文:
How to access struct's instance fields from a function?
问题
假设我有一个名为Graph
的结构体,如下所示:
type Graph struct {
nodes []int
adjList map[int][]int
}
// 结构体的一些方法
// 构造函数
func New() *Graph {
g := new(Graph)
g.adjList = make(map[int][]int)
return g
}
现在,我使用aGraph := New()
创建了一个该结构体的新实例。
如何访问这个特定实例的Graph
结构体的字段(aGraph
)?
换句话说,如何从另一个顶层函数中访问aGraph
的nodes
数组(例如)?
非常感谢您的帮助!
英文:
Assuming, that I have a Graph
struct, like so:
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
}
Now, I create a new instance of that struct, with: aGraph := New()
.
How do I access the fields of this particular instance of the Graph
struct (aGraph
)?
In other words, how do I access aGraph
's version of the nodes
array, (from within another top-level function for example)?
Any help is extremely appreciated!
答案1
得分: 1
这是一个示例:
package main
import (
"fmt"
)
// 示例结构体
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] map[0:[1990 1991 1992] 1:[1890 1891 1892] 2:[1890 1891 1892]]}
英文:
Here is one example:
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)
}
Output:&{[1 2 3 4 5] map[0:[1990 1991 1992] 1:[1890 1891 1892] 2:[1790 1791 1792]]}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论