dongren4147 2019-01-06 04:37
浏览 52

将查询结果从结构转换为另一个Golang包的字符串

I have searched for a solution on the net and in SO, but found nothing that apply to return values. It is a simple sql query with several rows that I want to return. Error handling not included:

func Fetch(query string) (string) {

    type User struct{
        id string
        name string
    }

    rows, err := db.Query(query)

    users := make([]*User, 0)
    for rows.Next() {
      user := new(User)
      err := rows.Scan(&user.id, &user.name)
      users = append(users, user)
    }

    return(users)
}

I get this error when compiling:

cannot use users (type []*User) as type string in return argument

How should I do to get a correct return value?

The expected input is

JD John Doe --OR-- {id:"JD",name:"John Doe"}

  • 写回答

2条回答 默认 最新

  • doulingna9420 2019-01-06 07:38
    关注

    If you have to return a String you can use the encoding/json package to serialize your user object, but you have to use fields that begin with capital letters for them to be exported. See the full example:

    import (
        "encoding/json"
    )
    
    func Fetch(query string) (string) {
    
        type User struct{
            Id string  // <-- CHANGED THIS LINE
            Name string // <-- CHANGED THIS LINE
        }
    
        rows, err := db.Query(query)
    
        users := make([]*User, 0)
        for rows.Next() {
          user := new(User)
          err := rows.Scan(&user.id, &user.name)
          users = append(users, user)
        }
    
        return(ToJSON(users)) // <-- CHANGED THIS LINE
    }
    
    func ToJSON(obj interface{}) (string) {
        res, err := json.Marshal(obj)
        if err != nil {
          panic("error with json serialization " + err.Error())
        }
        return string(res)
    }
    
    评论

报告相同问题?

悬赏问题

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