亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 go 中設置一個方法以使用一片結構

在 go 中設置一個方法以使用一片結構

Go
婷婷同學_ 2022-06-21 16:40:04
//Creating a structuretype Vertex struct {   X, Y int}//Using Add() to add an element to the slice of structure, vfunc (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)}go tour 站點返回以下錯誤:無效的接收器類型 []Vertex([]Vertex 不是已定義的類型)v.Add undefined(類型[]Vertex沒有字段或方法Add)有人可以幫我弄清楚我到底哪里出錯了
查看完整描述

2 回答

?
largeQ

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)

}


查看完整回答
反對 回復 2022-06-21
?
溫溫醬

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-


查看完整回答
反對 回復 2022-06-21
  • 2 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號