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

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

Golang 接口方法鏈接

Golang 接口方法鏈接

Go
慕桂英546537 2023-07-04 15:42:04
我有一個Cells包含多種方法的接口type Cells interface{    Len() int    //....}具體實現有StrCells、IntCells、 、FloatCells,BoolCells均實現了上述方法。例如:type StrCells []stringfunc (sC StrCells) Len() int {return len(sC)}//...type IntCells []intfunc (iC IntCells) Len() int {return len(iC)}//...//....對于兩種具體類型 -IntCells和FloatCells- 我想實現僅適用于這些類型的特定功能。我創建了一個NumCells嵌入的新界面Cellstype NumCells interface{    Cells    Add(NumCells) interface{} // should return either IntCells or FloatCells }這是我對 IntCells 的實現Add():func (iC IntCells) Add(nC NumCells) interface{} {    if iC.Len() != nC.Len() {        // do stuff    }    switch nC.(type) {    case IntCells:        res := make(IntCells, iC.Len())        for i, v := range iC {            res[i] = v + nC.(IntCells)[i]        }        return res    case FloatCells:        res := make(FloatCells, iC.Len())        for i, v := range iC {            res[i] = float64(v) + nC.(FloatCells)[i]        }        return res    default:        // to come        return nil    }}這是我的問題/問題該函數有效,但是,我實際上希望該函數返回NumCells(即 IntCells 或 FloatCells),因此我可以像這樣進行方法鏈接a := columns.IntCells(1, 2, 4, 2)b := columns.IntCells{2, 3, 5, 3}c := columns.FloatCells{3.1, 2, 2.4, 3.2}d := a.Add(b).Add(c)Add()如果返回一個 則這是不可能的interface{}。但是,我無法使該功能正常工作。
查看完整描述

1 回答

?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

如果您NumCells這樣定義接口,它就可以工作:


type NumCells interface{

    Cells

    Add(NumCells) NumCells // returns either IntCells or FloatCells

}

然后,您需要同時使用IntCells和FloatCells來實現Add并返回其中一種類型。


這是一個工作場所,使用方法鏈接并打印結果:


https://play.golang.org/p/W7DzcB4A3NH


正如評論中所述,在使用接口時,人們通常希望使每種類型與其余實現無關,并且只使用沒有類型開關的接口。


避免在 的實現中進行這些類型切換的一種方法Add可能是在 中添加另一種方法,以NumCells將特定位置作為float64.


type NumCells interface{

    Cells

    Add(NumCells) NumCells // returns either IntCells or FloatCells

    GetCell(index int) float64

}

這樣您就可以獲取該值,而無需斷言特定類型。


由于IntCells無法容納float64值,它仍然需要創建 aFloatCells來返回它,如果我們想避免IntCells這樣做,我們需要使用工廠模式或類似的方式以某種方式抽象對象的創建。


查看完整回答
反對 回復 2023-07-04
  • 1 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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