如何从函数中访问struct的实例字段?

时间:2015-02-23 00:07:41

标签: struct go visibility instance-variables

假设我有一个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数组(例如,来自另一个顶级函数)?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

以下是一个例子:

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] map [0:[1990 1991 1992] 1:[1890 1891 1892] 2:[1790 1791 1792]]}