gpt4 book ai didi

inheritance - Go "inheritance"- 在结构中使用匿名类型作为方法参数

转载 作者:IT王子 更新时间:2023-10-29 01:06:44 27 4
gpt4 key购买 nike

我正在尝试巩固 Go 提供的继承概念(也许是“组合”而不是纯粹的继承)。但是,我无法理解为什么我不能将“父”类型用作 func 参数来生成作用于该参数的通用函数。

package main

import "log"

type Animal struct {
Colour string
Name string
}

type Dog struct {
Animal
}

func PrintColour(a *Animal) {
log.Printf("%s\n", a.Colour)
}


func main () {
a := new (Animal)
a.Colour = "Void"
d := new (Dog)
d.Colour = "Black"

PrintColour(a)
PrintColour(d)
}

假设我的理解不正确,我怎样才能在 Go 中实现我想要的?

编辑注意:

  • 我不想将行为附加到结构

  • 我想将指针类型保留为方法参数,因为我正在单独处理一个宠物项目,这需要我先操作传入的结构,然后再对其执行操作。

    <
  • 实际上,我的 Dog 结构会有额外的字段/成员;希望这不会进一步搅浑水

最佳答案

到目前为止,我喜欢这里的答案,我想添加一个允许您使用接口(interface)对传入的接口(interface)进行静态类型检查的答案:

package main

import (
"fmt"
)

type Animalizer interface {
GetColour() string
}

type Animal struct {
Colour string
Name string
}

type Dog struct {
Animal
}

func (a *Animal) GetColour() string {
return a.Colour
}

func PrintColour(a Animalizer) {
fmt.Print(a.GetColour())
}

func main() {
a := new(Animal)
a.Colour = "Void"
d := new(Dog)
d.Colour = "Black"

PrintColour(a)
PrintColour(d)
}

On the playground

可以向 Dog 添加更多字段。与 Uriel 的答案的不同之处在于,如果传入的不是实现 Animalizer 的结构,那么调用 PrintColour 将在编译时失败。

此外,您不必使用类型切换,因为编译器知道 Animalizer 正在实现 GetColour

最后,行为(打印)与结构分离,GetColour 只返回颜色。

关于inheritance - Go "inheritance"- 在结构中使用匿名类型作为方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21527489/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com