SoFunction
Updated on 2025-03-03

Return statement in go language

1. Basic syntax and description

In Go language, in addition to goto, break and continue, jump control statements can also use return. If the return statement is used in an ordinary function, it means that the function will be jumped out and the code after return in the function will no longer be executed, which can be understood as a terminating function. If the return statement is used in the main function, it means terminating the main function, that is, terminating the running of the program.

The go function supports returning multiple values, which is not available to other programming languages.

func  Function name(List of formal parameters)(Return value type list){
​	Statement
​	returnReturn to the value list
}
  • 1. If multiple values ​​are returned, and when accepting, it is desired to ignore a certain return value, then use the _ symbol placeholder to ignore it.
  • 2. If there is only one return value (return value type list) you can not write ()

Case demonstration:

package main
import (
	"fmt"
)
func test(n1 int){
	n1 = n1 + 1
	("test() n1=",n1)
}
func getSum(n1 int,n2 int) int {
	sum := n1 + n2
	("getSum sum=",sum)
	return sum
}
func getSumAndSub(n1 int,n2 int)(int,int){
	sum := n1 + n2
	sub := n1 - n2
	return sum,sub
}
func main(){
	n1 := 10
	test(n1)
	("main() n1=",n1)

	sum := getSum(10,20)
	("main sum = ",sum)

	res1,res2 := getSumAndSub(8,2)
	("res1=%v res2=%v\n",res1,res2)

	_,res3 := getSumAndSub(3,9)
	("res3=",res3)
}

Execution results:

test() n1= 11
main() n1= 10
getSum sum= 30
main sum =  30
res1=10 res2=6
res3= -6

2. Recursive call of function

2.1 Basic introduction

A function has a call itself in the body of a function, which is called a recursive call

2.2 Introduction to recursive calls

package main
import (
	"fmt"
)
func test(n int){
	if n > 2 {
		n--
		test(n)
	}
	("n=",n)
}
func main() {
	test(4)
}

Execution results:

n= 2
n= 2
n= 3

3. Summary

  • 1. When executing a function, create a new protected independent space (new function stack)
  • 2. Local variables of functions are independent and will not affect each other.
  • 3. Recursion must be approximated to the condition of exiting recursion, otherwise it will be infinite recursion and a dead loop
  • 4. When a function is executed or encounters return, it will return. Whoever calls it will return the result to whom. At the same time, when the function is executed or returned, the change function itself will be destroyed by the system.

This is the end of this article about the return statement in Go language. For more related go language return content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!