如何从函数中访问结构体的实例字段?

huangapple go评论120阅读模式
英文:

How to access struct's instance fields from a function?

问题

假设我有一个名为Graph的结构体,如下所示:

  1. type Graph struct {
  2. nodes []int
  3. adjList map[int][]int
  4. }
  5. // 结构体的一些方法
  6. // 构造函数
  7. func New() *Graph {
  8. g := new(Graph)
  9. g.adjList = make(map[int][]int)
  10. return g
  11. }

现在,我使用aGraph := New()创建了一个该结构体的新实例。

如何访问这个特定实例的Graph结构体的字段(aGraph)?
换句话说,如何从另一个顶层函数中访问aGraphnodes数组(例如)?

非常感谢您的帮助!

英文:

Assuming, that I have a Graph struct, like so:

  1. type Graph struct {
  2. nodes []int
  3. adjList map[int][]int
  4. }
  5. // some methods on the struct
  6. // constructor
  7. func New() *Graph {
  8. g := new(Graph)
  9. g.adjList = make(map[int][]int)
  10. return g
  11. }

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

这是一个示例:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. // 示例结构体
  6. type Graph struct {
  7. nodes []int
  8. adjList map[int][]int
  9. }
  10. func New() *Graph {
  11. g := new(Graph)
  12. g.adjList = make(map[int][]int)
  13. return g
  14. }
  15. func main() {
  16. aGraph := New()
  17. aGraph.nodes = []int{1, 2, 3}
  18. aGraph.adjList[0] = []int{1990, 1991, 1992}
  19. aGraph.adjList[1] = []int{1890, 1891, 1892}
  20. aGraph.adjList[2] = []int{1890, 1891, 1892}
  21. fmt.Println(aGraph)
  22. }

输出:&{[1 2 3] map[0:[1990 1991 1992] 1:[1890 1891 1892] 2:[1890 1891 1892]]}

英文:

Here is one example:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. // example struct
  6. type Graph struct {
  7. nodes []int
  8. adjList map[int][]int
  9. }
  10. func New() *Graph {
  11. g := new(Graph)
  12. g.adjList = make(map[int][]int)
  13. return g
  14. }
  15. func main() {
  16. aGraph := New()
  17. aGraph.nodes = []int {1,2,3}
  18. aGraph.adjList[0] = []int{1990,1991,1992}
  19. aGraph.adjList[1] = []int{1890,1891,1892}
  20. aGraph.adjList[2] = []int{1890,1891,1892}
  21. fmt.Println(aGraph)
  22. }

Output:&{[1 2 3 4 5] map[0:[1990 1991 1992] 1:[1890 1891 1892] 2:[1790 1791 1792]]}

huangapple
  • 本文由 发表于 2015年2月23日 08:07:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/28665025.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定