【问题标题】:How to access struct's instance fields from a function?如何从函数访问结构的实例字段?
【发布时间】:2015-04-24 06:13:55
【问题描述】:

假设我有一个 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) 的这个特定实例的字段? 换句话说,我如何访问aGraphnodes 数组版本(例如,从另一个顶级函数中)?

非常感谢任何帮助!

【问题讨论】:

  • New函数一样;使用.。请注意,您的字段名称以小写字母开头,这意味着它们对包是私有的。您不能直接从另一个包访问它们。为此,请使字段名称以大写字母开头。

标签: struct go visibility instance-variables


【解决方案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]]}

【讨论】:

  • 这可以根据需要工作。这个问题实际上是完全不相关的,因为我使用的是go run,但我让程序分布在多个文件中,认为go run 实际上会包含所有需要的文件,如果我将它指向带有main() 的文件。原来go build 就是我们所需要的。
猜你喜欢
  • 2011-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
  • 2010-11-03
  • 2019-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多