Instagram
youtube
Facebook
Twitter

Functions

Functions

  • Functions are the proper way of developing a very long code and using various shortcodes
  • Functions handle a bundle of code and you can call a function in your main code just by giving the inputs and it’ll process the input accordingly returns the desired output.
//Sample code is as follows

func eatTacos() {

  fmt.Println("Yum!")

}

func main() {

  //calling the function here 

  eatTacos() //prints Yum! here

}
  • Functions with return type and scope example is as follows
func computeMarsYears(earthYears int) int {

  earthDays := earthYears * 365

  marsYears := earthDays / 687

  return marsYears

}


func main() {

  myage := 23

  //returning marsYear with myAge  as input 

  myMartianAge := computeMarsYears(myAge)

  fmt.Println(myMartianAge)

}
  • Functions with multiple return type can be used as follows
func GPA(midtermgrade float32, finalGrade float32) (string, float32) {

  averageGrade := (midtermGrade + finalGrade) / 2

  var gradeLetter string

  if averageGrade > 90 {

    gradeLetter = "A"

  } else if averageGrade > 80 {

    gradeLetter = "B"

  } else if averageGrade > 70 {

    gradeLetter = "C"

  } else if averageGrade > 60 {

    gradeLetter = "D"

  } else {

    gradeLetter = "F"

 }

  return gradeLetter, averageGrade

}