go - 了解 Go 中接口(interface)和指针的类型断言

标签 go

让我们考虑以下程序

type Fruit interface {
    Color() string
}

type Apple struct {
    color string
}

func (x *Apple) Color() string {
    return x.color
}

func (x *Apple) Compare(y Fruit) bool {
    _, ok := y.(*Apple)

    if ok {
        ok = y.Color() == x.Color()
    }

    return ok
}

func main() {
    a := Apple{"red"}
    b := Apple{"green"}

    a.Compare(&b)
}

现在,请注意最后一行 a.Compare(&b)。这里我传递一个指向Apple的指针。这正确工作,但请注意我的Compare 函数不接受指针(y Fruit)

现在,如果我将最后一行更改为 a.Compare(b) ,则会出现以下错误:

不能在 a.Compare 的参数中使用 b(Apple 类型)作为 Fruit 类型: 苹果没有实现Fruit(Color方法有指针接收器)

这里发生了什么?

最佳答案

出于 this answer 中概述的原因, Apple 没有实现 Fruit,但 *Apple 实现了。如果您在 Apple(而不是 *Apple)上定义 Color,则代码将编译:

package main

import (
    "fmt"
)
type Fruit interface {
    Color() string
}

type Apple struct {
    color string
}

func (x Apple) Color() string {
    return x.color
}

func (x Apple) Compare(y Fruit) bool {
    _, ok := y.(Apple)

    if ok {
        ok = y.Color() == x.Color()
    }

    return ok
}

func main() {
    a := Apple{"red"}
    b := Apple{"green"}

    fmt.Println(a.Compare(b))
}

关于go - 了解 Go 中接口(interface)和指针的类型断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43570119/

相关文章:

mongodb - 将动态数组结构传递给函数 Golang

go - Go中的替代导入语法

session - 为什么这个 gorilla session 代码不起作用?

database - 如何处理来自数据库的 nil 返回值?

function - Go 是否支持函数的类型转换/类型转换?

go - 如何启动和停止函数

go - 如何在 Golang 中查看导入的包

go - 获取 : go: error loading module requirements

html - 模板继承加载空页面

git - 如何将 Go 与私有(private) GitLab 存储库一起使用