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

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

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)?
换句话说,如何从另一个顶层函数中访问aGraphnodes数组(例如)?

非常感谢您的帮助!

英文:

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]]}

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:

确定