Go Function Return

Gayathri. B

 Returning Values from a Function

When a function needs to hand a result back to its caller, you must:

  • Declare the type of the value it will return (for example int, string, and so on) immediately after the parameter list.
  • Include a return statement inside the function body to send the desired value back.

Template:
func FunctionName(param1 type, param2 type) returnType {
    // perform operations here
    return value
}

Example 1:

package main
import "fmt"
// add returns the sum of two integers.
func add(x, y int) int {
return x + y
}
func main() {
fmt.Println(add(1, 2))
}

Example 2:

package main
import "fmt"
// sum demonstrates a named return value.
// The returned integer is named `total`, so we can use a “naked” return.
func sum(a, b int) (total int) {
total = a + b
return
}
func main() {
fmt.Println(sum(1, 2)) // Output: 3
}

Example 3:

package main
import "fmt"
// add returns the sum of x and y.
func add(x, y int) (sum int) {
sum = x + y
return // naked return: 'sum' is returned automatically
}
func main() {
fmt.Println(add(1, 2))
}   

 Storing Return Values in Variables

  • In Go, you can store a function's return value in a variable.

Example:

Here, the return value is stored in a variable named total:

package main
import "fmt"
func myFunction(x int, y int) (result int) {
result = x + y
return
}
func main() {
total := myFunction(1, 2)
fmt.Println(total)
}

Multiple Return Values

  • Go functions can return more than one value.

Example:

This function returns an integer and a string:
package main
import "fmt"

func myFunction(x int, y string) (int, string) {
return x + x, y + " World!"
}

func main() {
fmt.Println(myFunction(5, "Hello"))
}

Output:

10 Hello World!

Storing Multiple Return Values

  • You can store multiple return values in separate variables:

Example:

package main
import "fmt"
func myFunction(x int, y string) (int, string) {
return x + x, y + " World!"
}
func main() {
a, b := myFunction(5, "Hello")
fmt.Println(a, b)
}

Output:

10 Hello World!

Ignoring Return Values

  • If you don’t need all return values, use an underscore (_) to ignore one.

Example: Ignore the first value

package main
import "fmt"
func myFunction(x int, y string) (int, string) {
return x + x, y + " World!"
}
func main() {
_, b := myFunction(5, "Hello")
fmt.Println(b)
}

Output:

Hello World!

Example: Ignore the second value

package main
import "fmt"
func myFunction(x int, y string) (int, string) {
return x + x, y + " World!"
}
func main() {
a, _ := myFunction(5, "Hello")
fmt.Println(a)
}

Output:

10
  

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send