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

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

如何為結構指針上的方法定義接口

如何為結構指針上的方法定義接口

Go
LEATH 2022-10-24 09:04:20
對于structs,可以定義一個func可以更新struct變量的 a。有什么方法可以使用這些功能interface嗎?在以下代碼中,我嘗試創建一個最小示例來描述我的問題。和中struct的兩個被定義。兩者都有和功能。 函數計算形狀的周長。函數通過改變其屬性來增加形狀的周長。還定義了與方法簽名的接口。RectCirclestructPerimeterExpandPerimeterExpandShapePerimeterviewShapeData函數接受Shape類型的輸入參數。此函數查看形狀的數據并運行該Perimeter方法并查看形狀的周長。package mainimport "fmt"type Shape interface {    Perimeter() float64}type Rect struct {    width  float64    height float64}type Circle struct {    radius float64}func (s Rect) Perimeter() float64 {    return 2 * (s.width + s.height)}func (s Circle) Perimeter() float64 {    return 2 * 3.14 * s.radius}func (s *Rect) Expand(increaseValue float64) {    s.width += increaseValue / 2}func (s *Circle) Expand(increaseValue float64) {    s.radius += increaseValue / 3.14 / 2}func main() {    a := Circle{radius: 10.0}    b := Rect{width: 2.4, height: 5}    a.Expand(1)    viewShapeData(a)    b.Expand(1)    viewShapeData(b)}func viewShapeData(s Shape) {    fmt.Printf("value: %v, Type: %T, Perimeter: %f\n", s, s, s.Perimeter())}現在我正在尋找Expand一種在函數中調用方法的方法viewShapeData。我嘗試了不同的方法并在描述的代碼中應用了以下更改:type Shape interface {    Perimeter() float64    Expand(float64)}func main() {    a := Circle{radius: 10.0}    b := Rect{width: 2.4, height: 5}    viewShapeData(a)    viewShapeData(b)}func viewShapeData(s Shape) {    s.Expand(1)    fmt.Printf("value: %v, Type: %T, Perimeter: %f\n", s, s, s.Perimeter())}但是出現了這些錯誤:cannot use a (type Circle) as type Shape in argument to viewShapeData:        Circle does not implement Shape (Expand method has pointer receiver)cannot use b (type Rect) as type Shape in argument to viewShapeData:        Rect does not implement Shape (Expand method has pointer receiver)請給我一個解決方案或告訴我為什么 Golang 不支持這種編碼。
查看完整描述

1 回答

?
智慧大石

TA貢獻1946條經驗 獲得超3個贊

因此,如果您想使用指針接收器,您還應該將指針傳遞給采用接口的函數。


例如


func main() {

    a := Circle{radius: 10.0}

    b := Rect{width: 2.4, height: 5}

    

    a.Expand(1)

    viewShapeData(&a)


    b.Expand(1)

    viewShapeData(&b)

}

https://play.golang.com/p/pmHd5yl_v8p


查看完整回答
反對 回復 2022-10-24
  • 1 回答
  • 0 關注
  • 96 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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