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)
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:
Due to use of :=, local variables A and err gets declared with infered types.
The returned values of something({a:"abc",b:"def"}) gets assigned to local variables A and err.
Your function ends, local variables get removed from stack.
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 ?
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.