2015-02-08 23 views
3

我需要任何類型的幫助。Golang中的通用方法參數

我有一個功能,我需要接受其他類型具有ID屬性。

我嘗試過使用接口,但沒有爲我的ID屬性大小寫工作。下面是代碼:

package main 


import (
    "fmt" 
    "strconv" 
) 

type Mammal struct{ 
    ID int 
    Name string 
} 

type Human struct { 
    ID int 
    Name string 
    HairColor string 
} 

func Count(ms []Mammal) *[]string { // How can i get this function to accept any type not just []Mammal 
    IDs := make([]string, len(ms)) 
    for i, m := range ms { 
    IDs[i] = strconv.Itoa(int(m.ID)) 
    } 
    return &IDs 
} 

func main(){ 
    mammals := []Mammal{ 
    Mammal{1, "Carnivorious"}, 
    Mammal{2, "Ominivorious"}, 
    } 

    humans := []Human{ 
    Human{ID:1, Name: "Peter", HairColor: "Black"}, 
    Human{ID:2, Name: "Paul", HairColor: "Red"}, 
    } 
    numberOfMammalIDs := Count(mammals) 
    numberOfHumanIDs := Count(humans) 
    fmt.Println(numberOfMammalIDs) 
    fmt.Println(numberOfHumanIDs) 
} 

我得到這個

錯誤prog.go:39:不能用人類(鍵入[]人)類型[]哺乳動物參數計數

看去遊樂場瞭解更多詳情這裏http://play.golang.org/p/xzWgjkzcmH

回答

3

使用的接口,而不是具體類型,並使用embedded interfaces這樣的常用方法不必在這兩種類型列出:

type Mammal interface { 
    GetID() int 
    GetName() string 
} 

type Human interface { 
    Mammal 

    GetHairColor() string 
} 

這裏是這些接口的基礎上你的代碼中實現它使用embedded types(結構):

type MammalImpl struct { 
    ID int 
    Name string 
} 

func (m MammalImpl) GetID() int { 
    return m.ID 
} 

func (m MammalImpl) GetName() string { 
    return m.Name 
} 

type HumanImpl struct { 
    MammalImpl 
    HairColor string 
} 

func (h HumanImpl) GetHairColor() string { 
    return h.HairColor 
} 

但後來當然,在你的Count()功能,你可以只指的是方法,而不是現場的執行情況:

IDs[i] = strconv.Itoa(m.GetID()) // Access ID via the method: GetID() 

和創建哺乳動物片和人類:

mammals := []Mammal{ 
    MammalImpl{1, "Carnivorious"}, 
    MammalImpl{2, "Ominivorious"}, 
} 

humans := []Mammal{ 
    HumanImpl{MammalImpl: MammalImpl{ID: 1, Name: "Peter"}, HairColor: "Black"}, 
    HumanImpl{MammalImpl: MammalImpl{ID: 2, Name: "Paul"}, HairColor: "Red"}, 
} 

以下是Go Playground上的完整工作代碼。

+0

萬分感謝icza – 2015-02-08 13:59:58

5

在Go中,您無法完全按照您的要求進行操作。最近的方式來做事圍棋會是這樣的

type Ids interface{ 
Id() int 
} 

func (this Mammal) Id() int{ 
return this.ID 
} 

func (this Human) Id() int{ 
return this.ID 
} 


func Count(ms []Ids) *[]string { 
... 
    IDs[i] = strconv.Itoa(int(m.Id())) 
... 
} 

func main(){ 
    mammals := []Ids{ 
    Mammal{1, "Carnivorious"}, 
    Mammal{2, "Ominivorious"}, 
    } 

    humans := []Ids{ 
    Human{ID:1, Name: "Peter", HairColor: "Black"}, 
    Human{ID:2, Name: "Paul", HairColor: "Red"}, 
    } 
    ... 
} 

這裏工作example

+0

萬分感謝Uvelichitel – 2015-02-08 13:59:42