-4

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!

CuriOne
  • 103
  • 3
  • 8
  • The same way you do in the `New` function; using the `.`. Note that your field names start with a lower case letter, which means they are private to the package. You can't access them directly from another package. For that, make the field names start with an upper case letter. – jimt Feb 23 '15 at 00:22

1 Answers1

1

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

Craig Nicholson
  • 285
  • 2
  • 8
  • This works as needed. The problem was actually completely unrelated, as I was using `go run` but I had the program spread out across multiple files, thinking that `go run` would actually include all the files needed, if I point it to the one with `main()`. Turns out `go build` was all that's needed. – CuriOne Feb 23 '15 at 14:42