2 回答
TA貢獻2039條經驗 獲得超8個贊
定義方法時,接收者必須是命名類型,或指向命名類型的指針。
所以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)
}
TA貢獻1752條經驗 獲得超4個贊
//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-
- 2 回答
- 0 關注
- 141 瀏覽
添加回答
舉報
