How to give some value to []struct


(AkezhanOb1) #1
type example struct {
Example          string  `json:"example"`
Persons               []struct {
	FirstName     string `json:"firstName"`
	LastName      string `json:"lastName"`
	MiddleName    string `json:"middleName"`
	PhoneNumber   []struct {
		Carrier string `json:"carrier"`
                   Number string `json:"number"`
	} `json:"phoneNumber"`
   } `json:"persons"`
}

I have this example struct and I wanna create some instance of the struct

var ex example
ex.Example = "example"
ex.Persons[0].FirstName = "JHON"
ex.Persons[0].LastName = "DOE"
ex.Persons[0].MiddleName = "TEST"
ex.Persons[0].PhoneNumber[0].Carrier = "AT&T"
    ex.Persons[0].PhoneNumber[0].Number= "123545568"

but I get an error INDEX OUT OF BOUND, how can I assign value to the Person []Struct ?


(Yamil Bracho) #2

Please check :

  1. acbScoring does not exist (Maybe you mean “ex”)
  2. Create a struct for PhoneNumber and another for Person

For example :

package main

type PhoneNumber struct {
	Carrier string `json:"carrier"`
	Number  string `json:"number"`
}

type Person struct {
	FirstName    string        `json:"firstName"`
	LastName     string        `json:"lastName"`
	MiddleName   string        `json:"middleName"`
	PhoneNumbers []PhoneNumber `json:"phoneNumber"`
}

type example struct {
	Example string   `json:"example"`
	Persons []Person `json:"persons"`
}

func main() {
	var ex example
	ex.Example = "example"

	ex.Persons = make([]Person, 10)
	ex.Persons[0].FirstName = "JHON"
	ex.Persons[0].LastName = "DOE"
	ex.Persons[0].MiddleName = "TEST"

	ex.Persons[0].PhoneNumbers = make([]PhoneNumber, 10)
	ex.Persons[0].PhoneNumbers[0].Carrier = "AT&T"
	ex.Persons[0].PhoneNumbers[0].Number = "123545568"
}

(Norbert Melzer) #3

Alternatively you can also create the slice using literals:

type A struct {
  Field string
}

a := []A{
  A{ Field: "first" },
  A{ Field: "second" },
}

(Deimantas) #4

In your example you need to allocate space for Person slice because slices are not arrays. They are just like pointers, but with length and capacity parameters :slight_smile: You better define Person as separate type, then add it to your main structure like this:

type PhoneNumber struct {
	Carrier string `json:"carrier"`
	Number  string `json:"number"`
}

type Person struct {
	FirstName    string        `json:"firstName"`
	LastName     string        `json:"lastName"`
	MiddleName   string        `json:"middleName"`
	PhoneNumbers []PhoneNumber `json:"phoneNumber"`
}

type example struct {
	Example string   `json:"example"`
	Persons []Person `json:"persons"`
}

func main() {
	ex := example{
		Example: "example",
		Persons: []Person{
			Person{
				FirstName:  "JHON",
				LastName:   "DOE",
				MiddleName: "TEST",
				PhoneNumbers: []PhoneNumber{
					PhoneNumber{
						Carrier: "AT&T",
						Number:  "123545568",
					},
				},
			},
		},
	}
	fmt.Println(ex)
}