0

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) {
    d.name = name
    d.releaseYear = releaseYear
    d.director = director
}

func main() {
    dvdCollection := [15]DVD{}
    dvdCollection.AddDVD("Terminator1", 1984, "James Cameron")
}
icza
  • 389,944
  • 63
  • 907
  • 827
Gopythor
  • 35
  • 4

1 Answers1

0

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")
fmt.Println(dvdCollection[0])

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'

icza
  • 389,944
  • 63
  • 907
  • 827
  • Thank you for your support Plus question how to define strings for it? before it worked, but now it doesn't work. func (d *DVD) String() string { s := fmt.Sprintf("%s directed by %s released in %d", d.name, d.director, d.releaseYear) return s } fmt.Println(dvdCollection[0]) Result {Terminator1 1984 James Cameron} – Gopythor Feb 08 '22 at 10:20
  • @Gopyther Because your array contains non-pointer `DVD` values, and you defined your `String()` method with pointer receiver `*DVD`. Either specify it on non-pointer receiver like `func (d DVD) String()` or print a pointer value like `&dvdCollection[0]`. For details see https://stackoverflow.com/questions/53005752/different-behavior-when-printing-a-bytes-buffer-in-go/53005853#53005853 – icza Feb 08 '22 at 10:23