The function return value type must match the signature. A function can return multiple values or no value, the latter represented by (). The return statement ends the function early and returns the given value. Multiple return values use return to return multiple values.
Notes on Return Values of Go Language Functions
In the Go language, a function can return multiple values, or not at all. Return any value. For functions that return multiple values, the type of each return value should match the type declared in the function signature. If no value is returned, ()
should be used at the end of the function signature.
The following are some considerations for function return values:
func f() string
, then the function must return a value of type string. func f() (int, string)
, then the function can return an integer and a string. ()
. For example, if the function signature is func f()
, then the function does not return any value. return
statement in a function to end the function early and return the given value. If there are multiple return values in the function, you can use the return x, y
statement to return multiple values. Practical case:
The following code demonstrates how to use return value types and return
statements:
// 返回一个字符串的函数 func getName() string { return "John Doe" } // 返回一个整数和一个字符串的函数 func getFullName() (string, string) { return "John", "Doe" } // 不返回任何值的函数 func printHello() { fmt.Println("Hello, world!") } func main() { name := getName() fmt.Println(name) // 输出:John Doe firstName, lastName := getFullName() fmt.Println(firstName, lastName) // 输出:John Doe printHello() // 输出:Hello, world! }
The above is the detailed content of Things to note about golang function return values. For more information, please follow other related articles on the PHP Chinese website!