duanbiyi7319 2018-06-08 15:11 采纳率: 100%
浏览 64

从结构切片动态创建map [string] struct的通用函数

I have two different struct as mentioned below A abd B and two process functions. Is there any way by means of which i can write a common function to generate the map[string]struct for the both the struct. Moreover, is there any way using reflection given the struct name i can create the object of the same?

type A struct {
    name string
    // more fields
}


type B struct {
    name string
    // more fields  
}

func ProcessA(input []A) map[string]A {
    output := make(map[string]A)
    for _, v := range input {
         output[v.name] = v
    }
  return output
}


func ProcessB(input []B) map[string]B {
    output := make(map[string]B)
    for _, v := range input {
         output[v.name] = v
    }
  return output
}
  • 写回答

2条回答 默认 最新

  • duanjianshen4871 2018-06-08 16:05
    关注

    Idiomatic way in Go would be to use interface.

    type Named interface {
      Name() string
    }
    
    type letter struct {
      name string
    }
    
    func (l letter) Name() string {
      return l.name
    }
    
    
    type A struct {
        letter
        // more fields
    }
    
    
    type B struct {
        letter
        // more fields  
    }
    
    func ProcessNameds(input []Named) map[string]Named {
        output := make(map[string]Named, len(input))
        for _, v := range input {
             output[v.Name()] = v
        }
      return output
    }
    
    评论

报告相同问题?