Working with Go I was getting various errors trying to return a string as pointer while returning another value as well. Something like this (pls. excuse for this not being running code, I just wrote it to give a sense of what I want to do since I don't know how to exactly make it work):
func A (s string) *string, int {
// Stuff
return &a, b
}
*c, d := A("Hi there.")
When I try various combinations to say, return the string (var. a
) as a pointer I get various errors. It's easy and there's dozens of examples with a single variable returned but I'm not sure if it's possible with multiple return values.
Sorry if this seems like a very basic question, I'm still wrapping my mind around Go.
You can return multiple variables from a function:
func A (s string) (string, int) {
a := "hello world"
b := 99
return a, b
}
c, d := A("Hi there.")
One thing I would like to point out is that in Go, strings aren't pointers. In languages like C, you get used to thinking about a string
as a char*
, however in Go, a string
is treated as a primitive much like you would an int
.
This seems to trip people from time to time, however it is actually quite nice as you don't have to worry about pointers with strings.
If you find yourself in a situation where you want to return a nil
string (which you can't do because it's not a pointer), then you would return an empty string (""
).
Pointers: If you really want to do pointers...
func A (s string) (*string, int) {
a := "hello world"
b := 99
// NOTE: you have to have a variable hold the string.
// return a, &"hello world" // <- Invalid
return a, &b
}
// 'd' is of type *string
c, d := A("Hi there.")
var sPtr *string = d
var s string = *d // Use the * to dereference the pointer
as said here in golang spec, you are wrong in this part so:
func A (s string) (*string, int) {
//stuff
}
is the compilable code
@poy: I took your code and put in the playground and managed to get it working. I'm not sure what the issue was with why it wasn't working for me but there was probably something else going on. Anyway, with a little massaging this did work:
package main
import (
"fmt"
)
func A (s *string) (*string, int) {
b := 99
return s, b
}
func main() {
r := "Hi there."
var s *string = &r
c, d := A(s)
fmt.Println(*c, d)
}