
After presenting: the functions, its different syntaxes, how to call them. We will focus on the returns of these functions.
The GO language, allows us to make multiple results returns for a function.
func <FunctionName>(<Param1> type, <Param2> type, ...) <TypeRetour> { // Implémentation }
As far as the visibility of a function is concerned, in this sense we are talking about public or private. This is done by either putting the first letter in lowercase for a private function and a capital letter for a public service.
The returns of function
By definition, a function can only return a single result. Regardless of the type of base or type Struct.
But the creators of GO gave the possibility to the functions to return several results. And different type at the same time. This is what makes strength and is an essentialfeature_ in this language.
Here is the syntax of a function that returns two results:
func <FunctionName>(<Param1> type, <Param2> type, ...) <Type1>, <Type2> { // Implémentation return <valeur1>, <valeur2> }
Here is a simple example of calling and declaring a function. It will return a string set and an integer.
package main import "fmt" func main() { var name string = "John Doe" message, longeur := message(name) fmt.Printf("Voici un message:%s, le nom fait %d caractères. \n", message, longeur) } func message(nom string) (string, int) { return fmt.Sprintf("Hello dear %s.", nom), len(nom) }
In some cases, we may not need one or more value(s) in all returned values. There is a syntax or rather a symbol that will avoid making an assignment that will be useless.
The declaration of the function does not change at all, it is in the recovery of the values during the call. As shown on line 9 of the example, the underscore character _ is used. That if means that one does not need this result from the function.
Let us go back to the previous example
package main import "fmt" func main() { var name string = "John Doe" message, _:= message(name) fmt.Printf("Voici un message:%s. \n", message) } func message(nom string) (string, int) { return fmt.Sprintf("Hello dear %s", nom), len(nom) }
Looking at some native GO language packages will notice, that the majority of function calls return a couple. This couple is the result and possibly an error object if an error occurred in the function.
And now you know: