简体   繁体   English

接受通用结构的函数

[英]Function that accepts generic struct

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 . 假设我的结构是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? 我会以错误的方式处理吗?

This is considered the cornerstone (or more of a limitation) of Go's type system. 这被认为是Go类型系统的基石(或更多的限制)。 struct{} is an unnamed type that is different from struct{ field1 int } and of course is not the same as OrderRevenue{} . struct{}是与struct{ field1 int }不同的未命名类型,当然与OrderRevenue{}

Go emphasizes abstraction through interfaces, and perhaps you should try that. Go强调通过接口的抽象,也许您应该尝试一下。 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. 在这种情况下,您还可以使用所有类型都实现的空接口interface{} ,但是您必须递归地遍历该结构以进行手动类型声明。 The best approach in Go is to know the shape of your data in advance, at least partially. Go中最好的方法是至少部分地提前知道数据的形状。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM