英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论