Accessing struct from another package

How can I access struct created from one package from another package?

package a

func Somefunction() {
	A,err := something({a:"abc",b:"def"})  // returns pointer to struct
}

package b

// How can I access pointer to struct A from this package??

I try to make struct global like below but I get empty struct

package a

var A struct = {}

....  (same as before)

package b

fmt.Printf("%v", a.A)

And I get blank…

In the following snippet:

package a

var A struct = {}

func Somefunction() {
	A,err := something({a:"abc",b:"def"})  // returns pointer to struct
}

Which I assume is what you mean in your second example, the following happens when Somefunction() is getting called:

  1. Due to use of :=, local variables A and err gets declared with infered types.
  2. The returned values of something({a:"abc",b:"def"}) gets assigned to local variables A and err.
  3. Your function ends, local variables get removed from stack.
  4. Global variable A hasn’t been touched during all of this.

You probably want to use:

package a

var A struct = {}

func Somefunction() {
	var err error
	A, err = something({a:"abc",b:"def"})  // returns pointer to struct
}

Or even better:

package a

var A struct = {}

func Somefunction() (struct, error) { // or whatever the real return type of `something()` is.
	return something({a:"abc",b:"def"})  // returns pointer to struct
}

Try to avoid shared mutable global state, it will make it hard if not impossible to debug your code properly.

Love your answer on 1. Due to use of := , local variables A and err gets declared with infered types. !!! thank you

However, can you elaborate on

“Try to avoid shared mutable global state, it will make it hard if not impossible to debug your code properly.”

Can you think of any ways to use struct created from another package in other package without using global variable to pass the data struct that was created from func ?

Well the problem is, I really have no clue what your final goal is. Though as I said, just returning a value is probably the best.

So more details with the code and I need to separate them into 2 packages

package a

func Somefunction() {
	A, err := something({a:"abc",b:"def"})
}

func DoSomethingWithMovie(A) {
	// do something
}


package b

func Router() *mux.Router {
	router.HandleFunc("/movie", movie).Methods("POST")
	router.HandleFunc("/music", music).Methods("POST")
}

func movie {
	a.DosomethingWithMovie(A)
}

Sorry, I have no clue what that code should explain.

Though it seems as if you want to build some HTTP frontend to your movie and music database, so it is probably best to also store your data in a proper database rather than in memory.

fair enough… thank you… You spotting := was huge for me