简体   繁体   中英

Golang Structs/Interfaces

I'm trying to do something to bring the SQL results dynamically structure, basically I want to run a function by passing the rows and the structure(to get the data type and make one) and return in interface array.

Anyone know how I can do?

I dont want pass the direct "User" struct as param.. that is not dynamically

type User struct{
   Id_user int `json:"id_user"`
   Name string `json:"name"`
   Email string `json:"email"`
   Username string `json: "username"`
}

func main() {
  var user User
  rows, _ := db.Query("SELECT id_user, name, email, username FROM users")
  json.NewEncoder(w).Encode(StructRow(user, rows)) 
}

func StructRow(u interface{}, rows *sql.Rows)[]interface{}{
   var data []interface{}
   for rows.Next() {

      //How i can create a "user" here, dynamically
      //for Example
      //var user reflect.TypeOf(u)

      _ = rows.Scan(StrutForScan(&user)...)
      data = append(data, user)
   }
   return data
}

func StrutForScan(u interface{}) []interface{} {
   val := reflect.ValueOf(u).Elem()
   v := make([]interface{}, val.NumField())
   for i := 0; i < val.NumField(); i++ {
      valueField := val.Field(i)
      v[i] = valueField.Addr().Interface()
   }
   return v
}

Changing your function StructRow to

 func StructRow(u interface{}, rows *sql.Rows) []interface{} {
    var data []interface{}
    for rows.Next() {

         t := reflect.TypeOf(u)
         val := reflect.New(t).Interface()

         errScan := rows.Scan(StrutForScan(val)...)
         if errScan != nil {
             //proper err handling
         }
         data = append(data, val)
    }
    return data
 }

will fix it. I guess. For more on reflect package go to: https://golang.org/pkg/reflect/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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