drkjzk3359 2018-04-18 13:26
浏览 38
已采纳

用作函数参数的任意结构片的接口(golang)

I have two different types of structs in my app.

I'll show it as a simplified example:

type typeA struct {
    fieldA1 int
    fieldA2 string
}

type typeB struct {
    fieldB1 float32
    fieldB2 bool
}

First I init slices of them, then I want to store them in DB.

a := []typeA{
    {10, "foo"},
    {20, "boo"},
}
b := []typeB{
    {2.5, true},
    {3.5, false},
}

My first attempt was to iterate over first slice, then over second slice. It works just fine, but doesn't look DRY. The code is clearly duplicated:

printBothArrays(a, b)

// ...

func printBothArrays(dataA []typeA, dataB []typeB) {
    // Not DRY
    for i, row := range dataA {
        fmt.Printf("printBothArrays A row %d: %v
", i, row)
    }
    for i, row := range dataB {
        fmt.Printf("printBothArrays B row %d: %v
", i, row)
    }
}

A wrong way to make it DRY is to split it into 2 functions:

printArrayA(a)
printArrayB(b)

// ...

func printArrayA(data []typeA) {
    // Not DRY too, because the code is just split between 2 funcs
    for i, row := range data {
        fmt.Printf("printArrayA row %d: %v
", i, row)
    }
}

func printArrayB(data []typeB) {
    // Not DRY too, because the code is just split between 2 funcs
    for i, row := range data {
        fmt.Printf("printArrayB row %d: %v
", i, row)
    }
}

These two functions' signatures are different, but the code is just the same!

I thought of an universal function which can take any []struct and just store it. As my store function can take any interface{}, I thought of this:

func printArrayAny(data [](interface{})) {
    for i, row := range data {
        fmt.Printf("printArrayAny row %d: %v
", i, row)
    }
}

But I've tried different ways and I can't match any shared interface. I'm getting errors like:

cannot use a (type []typeA) as type []interface {} in argument to printArrayAny

I don't really want to make any heavy lifting like converting it to []map[string]interface, or using reflect, as both slices are really big.

Is there a way to modify printArrayAny so it can receive and iterate over any arbitrary []struct ?

Go playground link: https://play.golang.org/p/qHzcQNUtLIX

  • 写回答

1条回答 默认 最新

  • 普通网友 2018-04-18 13:35
    关注

    Use the reflect package to iterate over arbitrary slice types:

    func printArrayAny(data interface{}) {
        v := reflect.ValueOf(data)
        for i := 0; i < v.Len(); i++ {
            fmt.Printf("printArrayAny row %d: %v
    ", i, v.Index(i).Interface())
        }
    }
    

    Playground Example.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。