struct - 如何从函数访问结构的实例字段?

标签 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 数组(例如,从另一个顶级函数中)?

非常感谢任何帮助!

最佳答案

举个例子:

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

关于struct - 如何从函数访问结构的实例字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28665025/

相关文章:

c++ - 将光标位置存储在类对象中(ncurses c++)

c - 使用 uint32_t 和 GCC 原子指令 union 32 位结构

c - 用于分配结构散列键的全局变量的替代方案

goroutine race condition 解决方案

regex - Go中字符串末尾的正则表达式匹配失败

go - 在Windows中将gossagger替换为另一个版本

javascript - 链接到网站中被隐藏/显示 JavaScript 函数隐藏的部分

c - 如果只使用第一个元素,我是否必须为整个结构分配内存?

java - JDialog 不可见

excel - 如何: Excel 2003 macro to sum visible values only?