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

旅游网站返回以下错误:

无效接收器类型[]顶点([]顶点不是定义的类型(

v。添加未定义(类型[]Vertex没有字段或方法Add(

有人能帮我弄清楚到底在哪里出错吗

定义方法时,接收器必须是命名类型或指向命名类型的指针。

因此func (v []Vertex) Add() { ... }无效,因为[]Vertex不是命名类型或指向命名类型的指针。

如果要在顶点切片上使用方法,则需要一个新类型。例如:

type Vertices []Vertex
func (v *Vertices) Add() {
*v = append(*v, Vertex{2, 3})
}

整个程序将是这样的:

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-

最新更新