在 Go 中创建一个方法来操作结构体切片
时间:2024-03-01
浏览:247
作者:佚名
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《在 Go 中创建一个方法来操作结构体切片》,聊聊,希望可以帮助到正在努力赚钱的你。
问题内容
//Creating a structure
type Vertex struct {
X, Y int
}
//Using Add() to add an element to the slice of structure, v
func (v []Vertex) Add() {
v = append(v, Vertex{2,3})
}
func main() {
v:= make([]Vertex, 2, 2) //Creating a slice of Vertex struct type
v.Add()
fmt.Println(v)
}
gotour 网站返回以下错误:
无效的接收者类型 []vertex([]vertex 不是定义的类型)
v.add undefined(类型[]vertex没有字段或方法add)
有人可以帮我看看我到底哪里出了问题
解决方案
定义方法时,接收者必须是命名类型或指向命名类型的指针。
因此 func (v []vertex) add() { ... } 无效,因为 []vertex 不是命名类型或指向命名类型的指针。
如果您希望在顶点切片上使用方法,则需要一个新类型。例如:
type vertices []vertex
func (v *vertices) add() {
*v = append(*v, vertex{2, 3})
}
The whole program will be like this:
package main
import "fmt"
type vertex struct {
x, y int
}
type vertices []vertex
func (v *vertices) add() {
*v = append(*v, vertex{2, 3})
}
func main() {
v := make([]vertex, 2, 2) //creating a slice of vertex struct type
(*vertices)(&v).add()
fmt.println(v)
}//Creating a structure
type Vertex struct {
X, Y int
}
type Verices struct{
Vertices []Vertex
}
func (v *Verices) Add() {
v.Vertices = append(v.Vertices, Vertex{2,3})
}
func main() {
v:= Verices{}
v.Add()
fmt.Println(v)
}
您不能在切片上调用 add ,也不能在其上定义方法,但您可以将切片包装在结构中并在其上定义方法。
查看实际操作:
https://play.golang.org/p/NHPYAdGrGtp
https://play.golang.org/p/nvEQVOQeg7-
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在 Go 中创建一个方法来操作结构体切片》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
11.29
11.29
热门专题
