Skip to content
Related Articles

Related Articles

Golang Program that Uses Named Return Values and Defaults
  • Last Updated : 17 May, 2020

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:




// 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))
}

Example:

Displaying Default Values For Named Return Values
0 0

Displaying Assigned Values For Named Return Values
2499 7499

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :