第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

Golang 接口方法鏈接

Golang 接口方法鏈接

Go
慕桂英546537 2023-07-04 15:42:04
我有一個(gè)Cells包含多種方法的接口type Cells interface{    Len() int    //....}具體實(shí)現(xiàn)有StrCells、IntCells、 、FloatCells,BoolCells均實(shí)現(xiàn)了上述方法。例如:type StrCells []stringfunc (sC StrCells) Len() int {return len(sC)}//...type IntCells []intfunc (iC IntCells) Len() int {return len(iC)}//...//....對(duì)于兩種具體類型 -IntCells和FloatCells- 我想實(shí)現(xiàn)僅適用于這些類型的特定功能。我創(chuàng)建了一個(gè)NumCells嵌入的新界面Cellstype NumCells interface{    Cells    Add(NumCells) interface{} // should return either IntCells or FloatCells }這是我對(duì) IntCells 的實(shí)現(xiàn)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    }}這是我的問(wèn)題/問(wèn)題該函數(shù)有效,但是,我實(shí)際上希望該函數(shù)返回NumCells(即 IntCells 或 FloatCells),因此我可以像這樣進(jìn)行方法鏈接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()如果返回一個(gè) 則這是不可能的interface{}。但是,我無(wú)法使該功能正常工作。
查看完整描述

1 回答

?
郎朗坤

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊

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


type NumCells interface{

    Cells

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

}

然后,您需要同時(shí)使用IntCells和FloatCells來(lái)實(shí)現(xiàn)Add并返回其中一種類型。


這是一個(gè)工作場(chǎng)所,使用方法鏈接并打印結(jié)果:


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


正如評(píng)論中所述,在使用接口時(shí),人們通常希望使每種類型與其余實(shí)現(xiàn)無(wú)關(guān),并且只使用沒(méi)有類型開關(guān)的接口。


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


type NumCells interface{

    Cells

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

    GetCell(index int) float64

}

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


由于IntCells無(wú)法容納float64值,它仍然需要?jiǎng)?chuàng)建 aFloatCells來(lái)返回它,如果我們想避免IntCells這樣做,我們需要使用工廠模式或類似的方式以某種方式抽象對(duì)象的創(chuàng)建。


查看完整回答
反對(duì) 回復(fù) 2023-07-04
  • 1 回答
  • 0 關(guān)注
  • 160 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)