如何在Golang中加载Array中的struct方法

huangapple go评论88阅读模式
英文:

How to load method for struct in Array in Golang

问题

你好,现在我正在尝试将Java代码转换为Go代码。

但是我在使用为结构声明的方法时遇到了问题。

在将结构放入数组之前,方法可以被加载和使用。

但是在将其放入数组后,我无法调用它的方法。

你能检查一下下面的代码吗?

结果告诉我dvdCollection.DVD未定义(类型[15]*DVD没有字段或方法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")
}
英文:

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")
}

答案1

得分: 0

dvdCollection 是一个数组类型的值 ([15]DVD)。AddDVD() 方法是在 DVD 类型上定义的(更具体地说是 *DVD)。你只能在 *DVD 值上调用 AddDVD() 方法。

例如:

dvdCollection[0].AddDVD("Terminator1", 1984, "James Cameron")
// 这意味着 (&dvdCollection[0]).AddDVD("Terminator1", 1984, "James Cameron")
fmt.Println(dvdCollection[0])

这将输出(在 Go Playground 上尝试一下):

{Terminator1 1984 James Cameron}

还要注意,你正在使用一个 数组 ([15]DVD)。在 Go 中很少使用数组,你可能更想使用一个 切片。有关介绍和详细信息,请参阅博文:Arrays, slices (and strings): The mechanics of 'append'

英文:

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'

huangapple
  • 本文由 发表于 2022年2月8日 17:57:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/71031841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定