How to load method for struct in Array in Golang


Hello Now I am trying to convert Java to Go.

But I have problem with using method declared for structure.

Before put structure in Array, Method could be loaded and used.

After put it in array, I cannot call method for it.

Can you check below codes?

Result said me that dvdCollection.DVD undefined (type [15]*DVD has no field or method DVD)

type DVD struct {
    name        string
    releaseYear int
    director    string

func (d *DVD) AddDVD(name string, releaseYear int, director string) { = name
    d.releaseYear = releaseYear
    d.director = director

func main() {
    dvdCollection := [15]DVD{}
    dvdCollection.AddDVD("Terminator1", 1984, "James Cameron")


dvdCollection is a value of an array type ([15]DVD). The AddDVD() method is defined on the DVD type (more specifically *DVD). You can only call AddDVD() on a *DVD value.

For example:

dvdCollection[0].AddDVD("Terminator1", 1984, "James Cameron")
// which means (&dvdCollection[0]).AddDVD("Terminator1", 1984, "James Cameron")

This will output (try it on the Go Playground):

{Terminator1 1984 James Cameron}

Also note that you are using an array ([15]DVD). It’s rare to use an array in Go, you should likely want to use a slice. For an introduction and details, see blog post: Arrays, slices (and strings): The mechanics of ‘append’

Answered By – icza

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.