Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First argument to append must be slice

Tags:

go

I am having trouble calling the append function in Go

type Dog struct {
    color  string
}

type Dogs []Dog

I want to append "Dog" into "Dogs".

I tried doing this

Dogs = append(Dogs, Dog)

But I get this error

First argument to append must be slice; have *Dogs

Edit: Also, if I want to check if this Dog contains the color "white", for example. How would I call this?

 if Dog.color.contains("white") { 
    //then append this Dog into Dogs
 }
like image 390
pkmangg Avatar asked Feb 05 '17 10:02

pkmangg


2 Answers

As friends says it should not be a type, here is example can be helpful:

// Create empty slice of struct pointers.
Dogs := []*Dog{}
// Create struct and append it to the slice.
dog := new(Dog)
dog.color = "black"
Dogs = append(Dogs, dog)
like image 94
metmirr Avatar answered Oct 19 '22 18:10

metmirr


Dogs is a type not a variable, you probably meant to:

var Dogs []Dog
like image 5
Elad Avatar answered Oct 19 '22 16:10

Elad