【问题标题】:How to define interface for methods on struct pointer [duplicate]如何为结构指针上的方法定义接口[重复]
【发布时间】:2021-12-27 10:31:13
【问题描述】:

对于structs,可以定义一个可以更新struct变量的func。有什么方法可以使用interface中的这些功能吗?

在以下代码中,我尝试创建一个最小示例来描述我的问题。定义了RectCircle 中的两个structstructs 都有 PerimeterExpand 函数。 Perimeter 函数计算形状的周长。 Expand 函数通过更改其属性来增加形状的周长。还定义了带有Perimeter 方法签名的Shape 接口。

viewShapeData函数接受Shape类型的输入参数。该函数查看形状的数据并运行Perimeter 方法并查看形状的周长。

package main

import "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())
}

现在我正在寻找一种在viewShapeData 函数中调用Expand 方法的方法。我尝试了不同的方法并在描述的代码中应用了以下更改:

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 不支持这种编码。

【问题讨论】:

    标签: go go-interface


    【解决方案1】:

    所以,如果你想使用一个指针接收器,你也应该将一个指针传递给接受接口的函数。

    例如

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2019-06-26
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-26
      相关资源
      最近更新 更多