我已经在网上和SO中寻找解决方案,但没有发现适用于返回值的内容。这是一个简单的sql查询,我想返回几行。错误处理不包括在内:
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)
}
编译时出现此错误:
不能在返回参数中使用用户(类型[] * User)作为类型字符串
如何获取正确的返回值?
预期输入为
JD John Doe-或-{id:“ JD”,名称:“ John Doe”}
答案 0 :(得分:1)
将此添加到您的代码中:
type userSlice []*User
func (us userSlice) String() string{
var s []string
for _, u := range us {
if u != nil {
s = append(s, fmt.Sprintf("%s %s", u.id, u.name))
}
}
return strings.Join(s, "\n")
}
type User struct{
id string
name string
}
在Fetch函数中,替换最后一个return语句,如下所示:
func Fetch(query string) (string) {
// Note that we declare the User type outside the function.
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(userSlice(users).String()) // Replace this line in your code
}
答案 1 :(得分:0)
如果必须返回String,则可以使用encoding / json包序列化用户对象,但是必须使用以大写字母开头的字段来导出它们。查看完整的示例:
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)
}