Append to slice of struct

Implement append, to a slice of structs.

Page content

Lets append more values to a slice of struct, or an array of struct

Append values to a slice


type Key struct {
    Name string
}

type Keyboard struct {
    Keys []Key
}

func (kboard *Keyboard) AddKey(k Key) []Key {
	kboard.Keys = append(kboard.Keys, k)
	return kboard.Keys
}
func main() {

	// myKey1 := Key{Name: "Test Key 1", Role: "Upper"}
	myKey1 := Key{Name: "Test Key 1"}
    myKeyboard := Keyboard{}
	myKeyboard.AddKey(myKey1)
	myKeyboard.AddKey(Key{Name: "Test Key 2"})

    fmt.Println(len(myKeyboard.Keys))
	fmt.Println(myKeyboard.Keys)
}

To print out

2

[{Test Key 1 } {Test Key 2 }]

Append values to an array

type Key struct {
	Name string
}

type EnKeyboard struct {
	Keys [5]Key
}

func (kboard *EnKeyboard) AddKeyToEn(k Key) []Key {
	for i, v := range kboard.Keys {
		if v.Name == "" || len(v.Name) < 1 {
			kboard.Keys[i] = k
			return kboard.Keys[:]
		}
	}
	return kboard.Keys[:]
}
func main (){
    func main() {
	myKey1 := Key{Name: "En Key 1"}
	myEnKeyboard := EnKeyboard{}

	myEnKeyboard.AddKeyToEn(myKey1)
	myEnKeyboard.AddKeyToEn(Key{Name: "En Key 2"})

	fmt.Println(len(myEnKeyboard.Keys))
	fmt.Println(myEnKeyboard.Keys)
}

5

[{En Key 1} {En Key 2} {} {} {}]

Arrays guide. Slices guide. Struct guide.