String Return

Asked

Viewed 58 times

1

I’m trying to return a String format in a function, however error n occurs defined.

func descreve(x, y int) string{
    total := soma(x, y)
    return "%d + %d = %d", x, y, total
}

I don’t want to wear just one Println() to learn to return String.

1 answer

1


The undefined error is another problem because you have not defined the function you are using. The real problem reported in the question is that it is returning multiple values instead of making a formatting, which is what it is saying it wants. It’s not taking the Printf() that will work, this function does the formatting by you when going to print, but without anything it does not format magically, some function needs to be called to format the data.

See the documentation of Sprintf().

package main
import "fmt"

func descreve(x, y int) string {
    return fmt.Sprintf("%d + %d = %d", x, y, x + y)
}

func main(){
    fmt.Printf(descreve(1, 2))
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.