Golang Program that Uses Named Return Values and Defaults

Golang functions have special functionality that allows them to provide the name to the return values. These named return values can be used as arguments or variables. The named return values also use the default values for the data types like 0 for int type etc. To understand this concept let’s take an example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang Program that Uses Named
// Return Values and Defaults
package main
  
import "fmt"
  
// taking a function having named return
// values as dsa and placement
func courses(numbers []int) (dsa int, placement int) {
  
    // If the slice is at least two
    // elements set dsa and placement.
    // Else, leave the return values as zero.
    if len(numbers) >= 2 {
        dsa = numbers[0]
        placement = numbers[len(numbers)-1]
    }
    return dsa, placement
}
  
func main() {
  
    // For a zero-element
    // slice, these will return 0.
    fmt.Println("Displaying Default Values For Named Return Values")
    prices := []int{}
    fmt.Println(courses(prices))
    fmt.Println()
  
    fmt.Println("Displaying Assigned Values For Named Return Values")
  
    // The dsa and placement
    // values are set now
    prices = []int{2499, 7499}
    fmt.Println(courses(prices))
}

chevron_right


Example:

Displaying Default Values For Named Return Values
0 0

Displaying Assigned Values For Named Return Values
2499 7499
My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.