3 回答

TA貢獻1998條經驗 獲得超6個贊
Go 中沒有繼承(這是一個甜蜜點)。最接近的是嵌入父類型。
type Parent struct {}
func (p *Parent) doSomething() {
fmt.Println("Test")
}
type MyChild struct {
Parent
}
func main() {
child := &MyChild{}
child.doSomething() // print "Test"
}
查看https://golang.org/doc/effective_go.html#embedding

TA貢獻1779條經驗 獲得超6個贊
我相信你最終想要完成的事情類似于“模板方法”設計模式:
在軟件工程中,模板方法模式是一種行為設計模式,它在一個方法中定義算法的程序骨架,稱為模板方法,它將一些步驟推遲到子類中。
https://en.wikipedia.org/wiki/Template_method_pattern
AFAIK,在 Go 中實現這樣的事情的唯一正確方法是使用 @pie-o-pah 和 @icza 所說的接口。我說“類似的東西”,因為您不能將帶有接口的方法定義為接收者(即 Go 中沒有諸如部分抽象類型之類的東西)。
正確的實現如下所示:
package main
import "fmt"
// --------------------------
// define your purely abstract type as an interface
type MyParent interface {
doSomething() string
}
// define a function (your template method) which operates
// on that interface; an interface cannot be a function receiver,
// but it can always be a parameter
func internal(m MyParent) string {
return m.doSomething()
}
// define the implementation
type MyChild struct {}
// implement the methods for the interface
func (m *MyChild) doSomething() string {
return "Test"
}
// in Go any type which implements all methods in a given interface
// implements that interface implicitly, but you can "force" the
// compiler to check that for you using the following trick
// (basically try to assign a an instance of the interface to a variable,
// then discard it)
var _ MyParent = (*MyChild)(nil)
// -------------------------------
// test code
func main() {
m := &MyChild{}
fmt.Println(m.doSomething())
fmt.Println(internal(m))
}

TA貢獻1934條經驗 獲得超2個贊
//It's called interface
type Parent interface{
doSomething() string
}
//Use interface before defining implementation
func JustPrint(p Parent){
fmt.Println(p.doSomething())
}
//Define MyChild
type MyChild SomeType
//You do not have to implement interface explicitly
//Just to define method needed would be enough
func (mc MyChild) doSomething() string{
return "Test"
}
- 3 回答
- 0 關注
- 174 瀏覽
添加回答
舉報