drn9573 2015-04-24 00:19
浏览 39
已采纳

传递与指针接收器实现接口的对象

I understand that this has to do with the fact that Scale takes a pointer receiver. But I don't understand how I need to write PrintArea so this works.

package main

import (
        "fmt"
)

type Shape interface {
        Scale(num float64)
        Area() float64
}

type Square struct {
        edge float64
}

func (s *Square) Scale(num float64) {
        s.edge *= num
}

func (s Square) Area() float64 {
        return s.edge * s.edge
}

func PrintArea(s Shape) {
        fmt.Println(s.Area())
}

func main() {
        s := Square{10}
        PrintArea(s)
}

Here is the error I get as is.

# command-line-arguments
/tmp/sandbox126043885/main.go:30: cannot use s (type Square) as type Shape in argument to PrintArea:
    Square does not implement Shape (Scale method has pointer receiver)
  • 写回答

2条回答 默认 最新

  • dqyin0101 2015-04-24 00:36
    关注

    The Shape interface requires that the receiver has two methods - Scale and Area. Pointers to a type and the types themselves are considered different types in Go (so *Square and Square are different types).

    To implement the interface, the Area and Scale functions must be on either the type or the pointer (or both if you want). So either

    func (s *Square) Scale(num float64) {
        s.edge *= num
    }
    
    func (s *Square) Area() float64 {
        return s.edge * s.edge
    }
    
    func main() {
        s := Square{10}
        PrintArea(&s)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题