dts777777 2017-02-22 19:37
浏览 37
已采纳

对具有基础字段的任何结构体数组的调用方法

Let's say I have a bunch of structs (around 10).

type A struct {
    ID int64
    ... other A-specific fields
}

type B struct {
    ID int64
    ... other B-specific fields
}

type C struct {
    ID int64
    ... other C-specific fields
}

If I have an array of these structs at any given time (either []A, []B, or []C), how can I write a single function that pulls the IDs from the array of structs without writing 3 (or in my case, 10) separate functions like this:

type AList []A
type BList []B
type CList []C

func (list *AList) GetIDs() []int64 { ... }
func (list *BList) GetIDs() []int64 { ... }
func (list *CList) GetIDs() []int64 { ... }
  • 写回答

3条回答 默认 最新

  • duanbo6871 2017-02-22 22:15
    关注

    With general method on the slice itself

    You can make it a little simpler if you define a general interface to access the ID of the ith element of a slice:

    type HasIDs interface {
        GetID(i int) int64
    }
    

    And you provide implementation for these:

    func (x AList) GetID(i int) int64 { return x[i].ID }
    func (x BList) GetID(i int) int64 { return x[i].ID }
    func (x CList) GetID(i int) int64 { return x[i].ID }
    

    And then one GetID() function is enough:

    func GetIDs(s HasIDs) (ids []int64) {
        ids = make([]int64, reflect.ValueOf(s).Len())
        for i := range ids {
            ids[i] = s.GetID(i)
        }
        return
    }
    

    Note: the length of the slice may be a parameter to GetIDs(), or it may be part of the HasIDs interface. Both are more complex than the tiny reflection call to get the length of the slice, so bear with me on this.

    Using it:

    as := AList{A{1}, A{2}}
    fmt.Println(GetIDs(as))
    
    bs := BList{B{3}, B{4}}
    fmt.Println(GetIDs(bs))
    
    cs := []C{C{5}, C{6}}
    fmt.Println(GetIDs(CList(cs)))
    

    Output (try it on the Go Playground):

    [1 2]
    [3 4]
    [5 6]
    

    Note that we were able to use slices of type AList, BList etc, we did not need to use interface{} or []SomeIface. Also note that we could also use e.g. a []C, and when passing it to GetIDs(), we used a simple type conversion.

    This is as simple as it can get. If you want to eliminate even the GetID() methods of the slices, then you really need to dig deeper into reflection (reflect package), and it will be slower. The presented solution above performs roughly the same as the "hard-coded" version.

    With reflection completely

    If you want it to be completely "generic", you may do it using reflection, and then you need absolutely no extra methods on anything.

    Without checking for errors, here's the solution:

    func GetIDs(s interface{}) (ids []int64) {
        v := reflect.ValueOf(s)
        ids = make([]int64, v.Len())
        for i := range ids {
            ids[i] = v.Index(i).FieldByName("ID").Int()
        }
        return
    }
    

    Testing and output is (almost) the same. Note that since here parameter type of GetIDs() is interface{}, you don't need to convert to CList to pass a value of type []C. Try it on the Go Playground.

    With embedding and reflection

    Getting a field by specifying its name as a string is quite fragile (think of rename / refactoring for example). We can improve maintainability, safety, and somewhat the reflection's performance if we "outsource" the ID field and an accessor method to a separate struct, which we'll embed, and we capture the accessor by an interface:

    type IDWrapper struct {
        ID int64
    }
    
    func (i IDWrapper) GetID() int64 { return i.ID }
    
    type HasID interface {
        GetID() int64
    }
    

    And the types all embed IDWrapper:

    type A struct {
        IDWrapper
    }
    
    type B struct {
        IDWrapper
    }
    
    type C struct {
        IDWrapper
    }
    

    By embedding, all the embedder types (A, B, C) will have the GetID() method promoted and thus they all automatically implement HasID. We can take advantage of this in the GetIDs() function:

    func GetIDs(s interface{}) (ids []int64) {
        v := reflect.ValueOf(s)
        ids = make([]int64, v.Len())
        for i := range ids {
            ids[i] = v.Index(i).Interface().(HasID).GetID()
        }
        return
    }
    

    Testing it:

    as := AList{A{IDWrapper{1}}, A{IDWrapper{2}}}
    fmt.Println(GetIDs(as))
    
    bs := BList{B{IDWrapper{3}}, B{IDWrapper{4}}}
    fmt.Println(GetIDs(bs))
    
    cs := []C{C{IDWrapper{5}}, C{IDWrapper{6}}}
    fmt.Println(GetIDs(cs))
    

    Output is the same. Try it on the Go Playground. Note that in this case the only method is IDWrapper.GetID(), no other methods needed to be defined.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果