On Tue, 14 Jan 2014 07:18:43 -0800 (PST)
Rylan Halteman <
rylan.h...@gmail.com> wrote:
> I have a structure:
>
> type ClientStruct struct {
> resp chan int64
> }
>
> but I get a compiler error when I try to initialise it:
>
> client := &lib.ClientStruct {
> resp: make(chan int64),
> }
>
> Error:
> unknown lib.ClientStruct field 'resp' in struct literal
>
> The problem seems to be that the ClientStruct is declared in a
> different file and package then where I initialise it, since when I
> move the structure over to the same file it works fine. Using
> lib.ClientStruct.resp, or ClientStruct.resp gives an invalid field
> name error.
Sure: according to the simple visibility rules implemented in Go,
only names starting with an uppercase letters are "exported" -- visible
in other packages (this does not apply to other files in the same
package). This is true not only for top-level functions and types but
also for struct members.
> Is there any way to initialise & use a data structure that is defined
> in another file or package?
There might be two solutions:
* Make the field named "Resp", not "resp" if you're okay with
any user of your package will be able to access this field directly.
* Provide a "constructor function" for your type which will return
a new properly initialized instance of it, like this:
func NewClientStruct(resp chan int64) &ClientStruct {
return &ClientStruct{resp: resp}
}
and then make the users of your package call this function:
client := lib.NewClientStruct(make(chan int64))