2017-02-20 23 views
0

如何將相同的方法應用於不同的類型而不需要在Go中重複代碼?我有type1和type2並想要應用方法Do()如何將相同的方法應用於Go中的不同類型?

type type1 struct { } 
type type2 struct { } 

我必須重複代碼,請參閱下文。 Go有靜態類型,所以類型必須在編譯期間確定。

func (p type1) Do() { } 
func (p type2) Do() { } 

這工作得很好..但我不喜歡重複的代碼

type1.Do() 
type2.Do() 
+3

如果,你想在你的'Do'功能使用類型之間有一些共性,可以封裝在一個接口和定義接口'Do'。如果你提供了更多關於你的類型和功能的信息,我或其他人可以給你一個具體的例子。 –

回答

3

邏輯如何去這裏目前還不清楚,但在進入一個常見的模式是封裝在另一個結構中的共享功能類型,然後將它嵌入到你的類型:

type sharedFunctionality struct{} 

func (*sharedFunctionality) Do() {} 

type type1 struct{ sharedFunctionality } 
type type2 struct{ sharedFunctionality } 

現在你可以在type1type2情況或任何其他類型的呼叫Do()你需要這個功能。

編輯:根據你的評論,你可以重新定義一些等價的類型,如t1t2遵循這樣所需的協議(具有Do()方法):

func main() { 
    var j job 

    j = new(t1) 
    j.Do() 

    j = new(t2) 
    j.Do() 
} 

type job interface { 
    Do() 
} 

type t1 another.Type1 

func (*t1) Do() {} 

type t2 yetanother.Type2 

func (*t2) Do() {} 

這裏的類型another.Type1yetanother.Type2不是由你定義的,而是一些其他的包裝設計師。但是,你可以做任何與t1t2邏輯需求 - 儘可能公共成員去,或者如果你願意與反思的東西:)

+0

thnx,但我不喜歡尋找共享字段。這些類型1和類型2的結構不是由我自己創建的,很長且很複雜。我寧願重複代碼;) – irom

2

你可以去拿最接近的是要有一種嵌入另一個爛攤子。

type Type1 struct {} 

func (t *Type1) Do() { 
    // ... 
} 

type Type2 struct { 
    *Type1 
} 

與此唯一的限制就是你的Do()功能將只能訪問的Type1的領域。

+0

我一定會盡快嘗試這一個,看起來像我想要的壁櫥,也許我會很好地訪問只有Type1的字段 – irom

1

我想,你可以在這裏使用接口。例如:

package main 

import "fmt" 

type testInterface interface { 
    Do() 
} 

type type1 struct{} 
type type2 struct{} 

func (t type1) Do() { 
    fmt.Println("Do type 1") 
} 

func (t type2) Do() { 
    fmt.Println("Do type 2") 
} 

func TestFunc(t testInterface) { 
    t.Do() 
} 

func main() { 
    var a type1 
    var b type2 

    TestFunc(a) 
    TestFunc(b) 

} 
+0

Thnx,我也試過了,但它仍然沒有'因爲實際上「Do type 1」與「Do type 2」相同, – irom

相關問題