Return query result to another Golang package


(Sibert) #1

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

What am I doing wrong?


(Benjamin Radovsky) #2

Hi @Sibert,

You are trying to return a slice of structs of type User, but the function defines that you are returning a string (string).

You probably want to define your User type outside of the function and have Fetch return that type. For example:

type User struct {
	id   string
	name string
}

func Fetch(query string) []*User {}

(Sibert) #3
type User struct{
    id string
    name string
}

func Fetch(query string,) []*User (string) {...

gives these errors

missing function body
syntax error: unexpected ( after top level declaration


(Benjamin Radovsky) #4

You still have the (string) there.

You want it to just look like this:

func Fetch(query string) []*User {...


(Benjamin Radovsky) #5

On a side note, you should also try to return every error and handle it where Fetch is being called.

Here is commonly how I would write your fetch function. (I probably wouldn’t personally pass the query in if I know what I’m already scanning but that’s something else).

https://play.golang.org/p/WbS6GFMCM4Q

This example won’t actually run because I’m not initializing db, but just for an example.


(Sibert) #6

Yes, it works. Thank you!

But how do I format the result to readable text or json:

%!s(*data.User=&{JD John Doe})

Should be like this (or json)

JD John Doe

Best done before return or after return?


(Benjamin Radovsky) #7

I would personally do it after it’s returned.

Have a look at the std JSON package and let me know if you have any problems with it or if you need an example. :slight_smile:

https://golang.org/pkg/encoding/json/

Edit: I still think you should read through the JSON lib, but here is an example if you get stuck:

https://play.golang.org/p/QGaAFvgTpZW