golang interface用法

楚天乐 2895 0 条

golang interface测试

很不爽这种一眼看过去看不出一个struct实现了哪个interface的奇怪设计。但路依然是要走的,真香。。

测试代码1

package main

import "fmt"

type Task interface{
    execute()
}

type CrontabTask struct{
}
func (task CrontabTask) execute() {
    fmt.Println("crontab task!")
}

type QueueTask struct{
}
func (task QueueTask) execute() {
    fmt.Println("queue task!")
}

type LoopTask struct{
}
func (task LoopTask) execute() {
    fmt.Println("loop task!")
}

type WrongTask struct{
}
func (task WrongTask) execute1() {
    fmt.Println("loop task!")
}

func main(){
    var task Task

    task = new (CrontabTask)
    task.execute()

    task = new (QueueTask)
    task.execute()

    task = new (LoopTask)
    task.execute()
}

输出

crontab task!
queue task!
loop task!

测试代码2

package main

import "fmt"

type Task interface{
    execute()
}

type CrontabTask struct{
}
func (task CrontabTask) execute() {
    fmt.Println("crontab task!")
}

type QueueTask struct{
}
func (task QueueTask) execute() {
    fmt.Println("queue task!")
}

type LoopTask struct{
}
func (task LoopTask) execute() {
    fmt.Println("loop task!")
}

type WrongTask struct{
}
func (task WrongTask) execute1() {
    fmt.Println("loop task!")
}

func main(){
    var task Task

    task = new (WrongTask)
    task.execute()
}

输出

# command-line-arguments
.\interface.go:36:7: cannot use new(WrongTask) (type *WrongTask) as type Task in assignment:
    *WrongTask does not implement Task (missing execute method)

总结

  1. 创建struct对象的时候,类型不匹配,会被发现并报错
type Task interface{
    execute()
}
type WrongTask struct{
}
func (task WrongTask) execute() {
    fmt.Println("loop task!")
}

这个样子,golang就会认为WrongTask实现了Task接口,因为有execute()

type Task interface{
    execute()
}
type WrongTask struct{
}
func (task WrongTask) execute1() {
    fmt.Println("loop task!")
}

这个样子,golang语法检查就会出错,认为WrongTask没有实现Task接口



发表我的评论
昵称 (必填)
邮箱 (必填)
网址
执行时间: 1713936007033.7 毫秒