Rohit Hazra
Rohit Hazra

Reputation: 667

Can i create a struct inside the package to use outside in main program

I was porting my npm nodule to go package and at one place i need to do this.

type Credentials struct {
    key string
    responseType  string
    subscription string
    locale string
}

type WwogcParams struct {
    name string
    value  string
}
func main() {
    param1 := WwogcParams{"q","Delhi"}
    wwogc := []WwogcParams{param1}

    credentials := Credentials{key: "keykeykle",responseType: "json",subscription: "premium",locale: "EN"}
....
}

The main function here is basically what the user will have to write but what I was thinking if the user can use the struct I have defined inside the package in his main() function.

Why I can't use the structure outside its package?

Upvotes: 2

Views: 745

Answers (1)

Grzegorz Żur
Grzegorz Żur

Reputation: 49161

Use uppercase names for the fields. Only uppercase names are visible outside the package.

package something

type Credentials struct {
   Key string
   ResponseType  string
   Subscription string
   Locale string
}

type WwogcParams struct {
    Name string
    Value  string
}

In main:

package main

import (
     "something"
)

func main() {
    param1 := something.WwogcParams {"q","Delhi"}
    wwogc := []something.WwogcParams {param1}
    credentials := something.Credentials {
        Key: "keykeykle", 
        ResponseType: "json",
        Subscription: "premium", 
        Locale: "EN"
    }
}

See Exported identifiers

Upvotes: 2

Related Questions