I want to declare a pointer to a struct globally so that I can access this pointer in other files within my package. How do I do that?
Details: Package Y has struct named "Cluster" and also some functions named NewCluster etc.
type Cluster struct {
}
func NewCluster(self *Node, credentials Credentials) *Cluster {
return &Cluster{
}
}
Now,from package "X" when I tried accessing above cluster as below, it works good
cluster := Y.NewCluster(node, credentials)
Now, I want to declare this 'cluster' as a global variable so that I can access it in other files of my "X" package. So, I am trying to declare it many ways but its not working. How do I declare it globally? and then how do I access it in other files of my "X"package or else in the same file (to invoke same NewCluster function)?
Edit: I tried declaring as var cluster Cluster, var *cluster Cluster , var cluster *Cluster etc. but nothing works.
The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at top level (outside any function) is the package block.
Go Language Specification: Scope
So a variable declared in one package file outside of a function should be available in any other package file.
I think all you're missing here is the package name for the Cluster type: you need a qualified identifier.
A qualified identifier is an identifier qualified with a package name prefix. Both the package name and the identifier must not be blank.
Go Language Specification: Qualified Identifiers
The type Cluster is defined in package Y, as is the function NewCluster. When you accessed NewCluster from package X, you used a qualified identifier by prefixing the function name with the package name and a dot:
cluster := Y.NewCluster(node, credentials)
When you're trying to reference a type in package Y from package X, you need to do it with a qualified identifier. For example:
var cluster *Y.Cluster