How to return from goroutine?

I have a function that returns several values (string, error)

connStr := s.Url
con, err := sql.Open("postgres", connStr)
if err != nil {

	log.Println(err)
	return nil, twirp.NewError(twirp.DataLoss, "DB ERROR")
}
defer con.Close()
var resId int32
err = con.QueryRow(`INSERT INTO info(userID, details) VALUES ($1, $2) RETURNING id`, 0, request.GetDetails()).Scan(&resId)
if err != nil {
	return nil, err
}

when I wrap this code inside anonymous goroutine

go func() {
	connStr := s.Url
	con, err := sql.Open("postgres", connStr)
	if err != nil {

		log.Println(err)
		return nil, twirp.NewError(twirp.DataLoss, "DB ERROR")
	}
	defer con.Close()
	var resId int32
	err = con.QueryRow(`INSERT INTO info(userID, details) VALUES ($1, $2) RETURNING id`, 0, request.GetDetails()).Scan(&resId)
	if err != nil {
		return nil, err
	}

}()

my return statement became invalid, how can I manage this?

Your go routine is like a little process in your main application. Don’t expect to return values from go routine with return instruction :face_with_hand_over_mouth: Eventualy use a global variable or a channel like in this example :smirk:

3 Likes

Looks to me you get an error, because you have an anonymous function returning a value, that go is not expecting to get, and doesn’t know how to handle. Why don’t you name the function and handle the returns accordingly ? You would have to follow the convention that a function needs to declare what is going to return func() ( return types) . If that is not an option, one could use global variables and change their value before the return is triggered.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.