为什么方法签名必须与接口方法完全匹配 [英] Why does method signature have to perfectly match interface method

查看:44
本文介绍了为什么方法签名必须与接口方法完全匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习Go,但在理解以下内容时遇到了困难:

I began to learn Go and have trouble understanding the following:

package main

import "fmt"

type I interface {
    foo(interface {})
}

type S struct {}

func (s S) foo(i int) {
    fmt.Println(i)
}

func main() {
    var i I = S{}
    i.foo(2)
}

此操作失败,并显示以下信息:

This fails with:

cannot use S literal (type S) as type I in assignment:
        S does not implement I (wrong type for foo method)
                have foo(int)
                want foo(interface {})

鉴于 int 实现了 interface {} 的事实,我不明白为什么Go不接受 foo(int)签名.谁能帮忙解释一下?

I don't understand why Go doesn't accept the foo(int) signature given the fact that int implements interface {}. Can anyone help with an explanation?

推荐答案

我认为您对界面的理解不够充分.Interface {}本身就是一种类型.它由两部分组成:基础类型和基础值.

I think your understanding of interface isn't sound. Interface{} itself is a type. It consists of two things : underlying type and underlying value.

Golang没有重载.Golang类型系统按名称匹配,并且要求类型保持一致

Golang doesn't have overloading. Golang type system matches by name and requires consistency in the types

因此,当您定义以接口类型作为参数的函数时:

So, when you are defining a function taking a interface type as a parameter:

foo(interface {})

这与采用int类型的函数不同:

This is a different function from a function taking int type:

foo(int)

因此,您应将以下行更改为

So you should change the following line to

func (s S) foo(i interface{}) {
    fmt.Println(i)
}

或更妙的是:

type I interface {
    foo()
}

type S struct {
    I int
}

func (s S) foo() {
    fmt.Println(s.I)
}

func main() {
    var i I = S{2}
    i.foo()
}

这篇关于为什么方法签名必须与接口方法完全匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆