猿问

Golang 结构/接口

我正在尝试做一些事情来动态地带来 SQL 结果结构,基本上我想通过传递行和结构来运行一个函数(以获取数据类型并制作一个)并在接口数组中返回。


有谁知道我该怎么做?


我不想将直接的“用户”结构作为参数传递..这不是动态的


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

}


肥皂起泡泡
浏览 153回答 1
1回答

开心每一天1111

将您的功能更改StructRow为&nbsp;func StructRow(u interface{}, rows *sql.Rows) []interface{} {&nbsp; &nbsp; var data []interface{}&nbsp; &nbsp; for rows.Next() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;t := reflect.TypeOf(u)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;val := reflect.New(t).Interface()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;errScan := rows.Scan(StrutForScan(val)...)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if errScan != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//proper err handling&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;data = append(data, val)&nbsp; &nbsp; }&nbsp; &nbsp; return data&nbsp;}会修复它。我猜。有关反射包的更多信息,请访问:https ://golang.org/pkg/reflect/
随时随地看视频慕课网APP

相关分类

Go
我要回答