dongshuzhuo5659 2016-05-18 11:21
浏览 137
已采纳

GoLang上的接口函数调用

I am having a problem go interfaces.

Here is my main.go file;

package main

import (
    "fmt"
    "bitbucket.org/xyz/trash/a"
)

// Second -
type Second interface {
    Area() float64
}

// Area -
func Area() float64 {
    return 2
}


func main() {

    r := new(a.Rect)

    n := new(Second)

    r.F = *n

    fmt.Println(r.Area()) 

}

And my other package, a.go;

package a

// First -
type First interface {
    Area() float64
}

// Rect -
type Rect struct {
    F First 
}

// Area -
func (r Rect) Area() float64 {
    return 1
}

I am expecting this line

fmt.Println(r.Area())

to print "2", not "1". What am i missing?

Thanks for your help.

  • 写回答

2条回答 默认 最新

  • doujiao1180 2016-05-20 22:17
    关注

    First, look at your code again. As written, a.Rect.Area() returns 1. It always returns 1. Set all the properties you like. It returns 1. Gnash your teeth and curse the gods. It returns 1. Because it's a function that returns 1. That's what it does.

    Write it like this:

    // Area -
    func (r Rect) Area() float64 {
        return r.F.Area()
    }
    

    ...and you'll panic because you've got another issue.

    Area() in main.go doesn't have a receiver. It has nothing to do with interfaces. It's just a function. No objects. No implementing anything. No polymorphism. No nothing.

    You've declared n as a pointer to an interface, not an implementation of an interface. It's nil. If you try to dereference it the whole world will come crashing down into the void.

    If you want to be able to call n.Area() then make Second a concrete type.

    (In main.go)

    // Second -
    type Second struct {}
    
    // Area -
    func (s Second) Area() float64 {
        return 2
    }
    

    Do you see the difference? Second is now a struct that implements the interface a.First because it is the receiver of an appropriate Area() method. Thus you will get the expected behavior.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3