Golang中的多态性是什么?

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

Polymorphism in Golang?

问题

我是你的中文翻译助手,以下是你提供的代码的翻译:

我对Go语言还比较新我已经使用面向对象编程(OOP)很长时间了现在我了解到Go语言通过组合来实现继承但是...我想在一个期望接收泛化类型的函数中传递一个特化类型

package main

import (
	"fmt"
)

type A struct {
	ONE int
}

type B struct {
	A
	ANOTHER int
}

func main() {
	fmt.Println("Hello, playground")

	a := A{1}
	b := B{a, 2}

	fmt.Println(a.ONE)
	fmt.Println(b.ANOTHER)
	
	takeA(&b)
}

func takeA(a *A) {

	fmt.Println(a.ONE)
}

当然,我可以使用takeA(&b.A),但这会破坏我试图建立的继承关系,因为一些A的字段/方法可能会在B中被隐藏。

有没有办法解决这个问题?或者我应该创建一个简单的接口,例如:

package main

import (
	"fmt"
)

type A struct {
	ONE int
}

func (a A) getOne() int{
	return a.ONE
}

type B struct {
	A
	ANOTHER int
}

type HasOne interface {
	getOne() int
}

func main() {
	fmt.Println("Hello, playground")

	a := A{1}
	b := B{a, 2}

	fmt.Println(a.ONE)
	fmt.Println(b.ANOTHER)
	
	takeA(b)
}

func takeA(a HasOne) {

	fmt.Println(a.getOne())
}

希望对你有帮助!

英文:

I am fairly new to Go and I have been doing OOP for a long time. Now, I understand that inheritance is done via composition but ... I'd like to send a specialization in a function expecting a generalization as such:

package main

import (
	"fmt"
)

type A struct {
	ONE int
}

type B struct {
	A
	ANOTHER int
}

func main() {
	fmt.Println("Hello, playground")

	a := A{1}
	b := B{a, 2}

	fmt.Println(a.ONE)
	fmt.Println(b.ANOTHER)
	
	takeA(&b)
}

func takeA(a *A) {

	fmt.Println(a.ONE)
}

Sure, I can do takeA(&b.A) but it defeats the hierarchy I am trying to set up as some A fields/method could be shadowed in B.

Is there a way around this? Or should I create a dumb interface such as:

package main

import (
	"fmt"
)

type A struct {
	ONE int
}

func (a A) getOne() int{
	return a.ONE
}

type B struct {
	A
	ANOTHER int
}

type HasOne interface {
	getOne() int
}

func main() {
	fmt.Println("Hello, playground")

	a := A{1}
	b := B{a, 2}

	fmt.Println(a.ONE)
	fmt.Println(b.ANOTHER)
	
	takeA(b)
}

func takeA(a HasOne) {

	fmt.Println(a.getOne())
}

答案1

得分: 5

在Go语言中没有继承。组合不会给你动态分派(当在同一段落中使用“多态”和“继承”时,通常会暗示动态分派):嵌入方法调用总是在嵌入字段上作为接收器进行,而不是在容器类型上进行。

英文:

There is no inheritance in Go. Composition doesn't give you dynamic dispatch (which is usually implied when 'polymorphism' and 'inheritance' are used in the same paragraph): the embedded method call always happens on the embedded field as a receiver, not on the container type it is embedded into.

huangapple
  • 本文由 发表于 2017年5月24日 03:15:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/44143265.html
匿名

发表评论

匿名网友

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

确定