强制Go类型实现接口

huangapple go评论85阅读模式
英文:

Forcing Go types to implement an interface

问题

在Go语言中,你不需要声明需要实现一个接口,你只需要直接实现它(这被称为"结构化类型",类似于动态语言中的"鸭子类型")。
如果你想要强制一个类型实现一个接口(就像在C#或Java中"继承"一个接口一样),该怎么办呢?换句话说,如果忘记实现一个接口(或者签名错误)是一个错误,并且你想要尽早捕捉到这个错误,最好的方法是什么?

英文:

In Go, you don’t state that you need to implement an interface, you just do it (it’s called ‘structural typing’ similar to ‘duck typing’ in dynamic languages).
What if you want to force a type to implement an interface (like when you ‘inherit’ an interface in C# or Java for instance)? In other words, what if forgetting to implement an interface (or getting the signature wrong) is a mistake and you want to catch that mistake early. What is the best way to do it?

答案1

得分: 4

你最好的做法是尝试将类型的实例分配给接口变量。

例如,你想确保类型A实现了Stringer接口。

你可以这样做:

var _ Stringer = new(A) // 或者
var _ Stringer = A{}

这是一个示例程序,其中A实现了接口,而B没有:

package main

import (
	"fmt"
)

type Stringer interface {
	String() string
}

type A struct {
}

func (a A) String() string {
	return "A"
}

type B struct {}

var _ Stringer = new(A)
var _ Stringer = new(B)

func main() {

	fmt.Println("Hello, playground")
}

这是Playground链接:play.golang

英文:

Best thing you may do is try to assign an instance of the type to a interface variable

For example you want to make sure type A implements Stringer interface.

You may do like this

var _ Stringer = new(A) //or
var _ Stringer = A{}

Here is the sample program, In the example A implements the interface and B does not

package main

import (
	"fmt"
)

type Stringer interface {
   String() string
}

type A struct {
}

func (a A) String() string {
    return "A"
}

type B struct {}


var _ Stringer = new(A)
var _ Stringer = new(B)

func main() {

	fmt.Println("Hello, playground")
}

Play link here : play.golang

答案2

得分: 0

完成@Sarathsp所说的内容:
基本上,通过声明一个接口类型的虚拟变量(下划线表示不使用),同时将你的类型的实例赋值给它,你会得到非常明确的编译时错误:

type MyType struct {
}

func (*MyType) Read() {

}

var _ io.Reader = &MyType{}


无法将MyType字面量(类型为*MyType)用作io.Reader类型的赋值:
    *MyType未实现io.Reader(缺少Read方法)

或者

无法将MyType字面量(类型为*MyType)用作io.Reader类型的赋值:
    *MyType未实现io.Reader(Read方法的类型错误)
            拥有Read()
            想要Read([]byte) (int, error)
英文:

To complete what @Sarathsp said:
Basically, by declaring a dummy variable (underscore means that it is not used) of the interface type while assigning an instance of your type to it, you get very explicit compile-time errors:

    type MyType struct {
    }
    
    func (*MyType) Read() {
    
    }
    
    var _ io.Reader = &MyType{}


cannot use MyType literal (type *MyType) as type io.Reader in assignment:
        *MyType does not implement io.Reader (missing Read method)

Or

cannot use MyType literal (type *MyType) as type io.Reader in assignment:
        *MyType does not implement io.Reader (wrong type for Read method)
                have Read()
                want Read([]byte) (int, error)

huangapple
  • 本文由 发表于 2016年12月26日 17:38:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/41329168.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定