亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go OOP 實現

Go OOP 實現

Go
至尊寶的傳說 2021-12-27 18:20:19
這個代碼片段在 Go 中應該是什么樣子的?當子類尚未定義時,如何從父類訪問子類的方法?class Parent {abstract class MyParent {   abstract function doSomething();   function internal() {       return static::doSomething();   }}class MyChild extends MyParent {   function doSomething() {       return 'Test';   }}
查看完整描述

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


查看完整回答
反對 回復 2021-12-27
?
哆啦的時光機

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))

}


查看完整回答
反對 回復 2021-12-27
?
撒科打諢

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"

}


查看完整回答
反對 回復 2021-12-27
  • 3 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號