Victor
Victor

Reputation: 1

How do I append to slice in struct of multidimensional in Go?

New to Go...

I have the following:

type class struct{
  Name    string
  Age     int
  Address string
  Phone.  int
}

SchoolClassList := [12][4]class{}

NewStudent := class{}

To start, I initialize for 12 because I will have 12 different grade levels for each class. And each class will start with 4 students. I want to be able to append to any of the class as more students arrive.

I tried doing the following to append to grade 2

SchoolClassList[2] = append(SchoolClassList[2],NewStudent

However I am getting the following error:

First argument to append must be a slice; have SchoolClassList[2] (variable of type [4]class

Upvotes: -2

Views: 51

Answers (1)

Learner
Learner

Reputation: 99

Append works on slices (you are using array).

use this

package main

import "fmt"

func main() {

    type class struct {
        Name    string
        Age     int
        Address string
        Phone   int
    }

    SchoolClassList := [12][]class{}

    fmt.Println("Before: ", SchoolClassList)

    NewStudent := class{}

    SchoolClassList[2] = append(SchoolClassList[2], NewStudent)

    fmt.Println("After", SchoolClassList)
}

Upvotes: 0

Related Questions