duan5731 2017-08-09 17:00
浏览 9
已采纳

接受通用结构的函数

Is it possible to have my function definition below accept any type of struct?

I've tried to refactor like so:

// This method should accept any type of struct
// Once I receive my response from the database,
// I scan the rows to create a slice of type struct.

func generateResponse(rows *sqlx.Rows, structSlice []struct{}, structBody struct{}) ([]struct{}, error) {
    for rows.Next() {

        err := rows.StructScan(&structBody)

        if err != nil {
            return nil, err
        }

        structSlice = append(structSlice, structBody)

    }

    err := rows.Err()
    if err != nil {
        return nil, err
    }

    return structSlice, nil
}

Assume my struct is of type OrderRevenue.

When I call the function above:

structSlice, err := generateResponse(rows, []OrderRevenue{}, OrderRevenue{})

The error I get is:

cannot use []OrderRevenue literal as type []struct{} in argument...

Am I going about this the wrong way?

  • 写回答

1条回答 默认 最新

  • duandoucou7200 2017-08-09 20:37
    关注

    This is considered the cornerstone (or more of a limitation) of Go's type system. struct{} is an unnamed type that is different from struct{ field1 int } and of course is not the same as OrderRevenue{}.

    Go emphasizes abstraction through interfaces, and perhaps you should try that. Here is the first take:

      type OrderRevenue interface {
              MarshalMyself() ([]byte, error)
      }
    
      type Anonymous struct {}
      func (a Anonymous) MarshalMyself() ([]byte, error) {
              // implementation's up to you
              return []byte{}, nil
      }
    
      // the function signature
      generateResponse(rows *sqlx.Rows, structSlice []OrderRevenue, structBody Body) ([]Body, error) {
              // ...
      }
    

    In this case you can also use empty interface interface{}, which all types implement, but you'll have to recursively go through the structure to do manual type assertion. The best approach in Go is to know the shape of your data in advance, at least partially.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度