doukaojie8573 2016-09-14 09:56
浏览 1723

Golang将列表对象转换为字符串

I have two structs:

type A struct {
    BankCode           string `json:"bankCode"`
    BankName           string `json:"bankName"`
}

And:

type B struct {
    A 
    extra           string `json:" extra"`
}

And two slices:
listsA []A and listsB []B I want to get bankCodes from listA and listB. bankcodes only contains bankcodes. It is a []string

It will be so easy as using two function.

func getBankCodes(data []A) []string {
    res := make([]string, len(data))
    for i := 0; i < len(data); i++ {
        res[i] = data[i].BankCode
    }
    return res
}

func getBankCodes(data []B) []string {
    res := make([]string, len(data))
    for i := 0; i < len(data); i++ {
        res[i] = data[i].BankCode
    }
    return res
}

How to use one common function ?

  • 写回答

2条回答 默认 最新

  • dqvj51875 2016-09-14 10:07
    关注

    Well the clean solution would be to use an interface, since go doesn't support classic inheritance, so something like []parentclass can't work. Interfaces however can only describe functions not a common field, so you have to implement a Getter (essentially).

    // GetBankCoder provides a function that gives the BankCode
    type GetBankCoder interface {
        getBankCode() string
    }
    
    // implement GetBankCoder for A (and indirectly for B)
    func (a A) getBankCode() string {
        return a.BankCode
    }
    

    and make your getBankCodes work on that interface type, notice the parameter of the function as well as the statement inside the loop:

    func getBankCodes(data []GetBankCoder) []string {  // <-- changed
        res := make([]string, len(data))
        for i := 0; i < len(data); i++ {
            res[i] = data[i].getBankCode()             // <-- changed
        }
        return res        
    }
    

    There are other solutions where the function parameter is of interface{} type and then reflection is used to assure you can actually do .BankCode, but I don't like those, as they are not adding more clarity either.

    ... However, I couldn't get the golang playground to make this work correctly without putting it into a []GetBankCoder var first, before giving it to the function.

    banks := make([]GetBankCoder, 0)
    banks = append(banks, A{ BankCode: "ABC", BankName: "ABC Bank"})
    getBankCodes(banks)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器