Learn
Learn Go: Functions
Multiple Return Values

Functions also have to ability to return multiple values. Check out the example below:

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 }

Above, after the parentheses which contain our parameters, we need to provide the types of the multiple returns wrapped in their own set of parentheses. The GPA() function will return 2 values, the first value is a string and the second value is an int32. Also, when we return multiple values, we use a single return keyword followed by the values separated by commas: gradeLetter, averageGrade. When we call the function:

func main() { var myMidterm, myFinal float32 myMidterm = 89.4 myFinal = 74.9 var myAverage float32 var myGrade string myGrade, myAverage = GPA(myMidterm, myFinal) fmt.Println(myAverage, myGrade) // Prints 82.12 B }

We’re able to call GPA() with the necessary arguments and it returns back both 82.12 and B which we print to the terminal.

Instructions

1.

We would like to use the information received in getLikesAndShares() inside our main() function.

Update getLikesAndShares() to return two ints.

2.

At the bottom of getLikesAndShares(), return the two variables likesForPost and sharesForPost.

3.

In main() use the variables likes and shares to store the results fromgetLikesAndShares().

Folder Icon

Take this course for free

Already have an account?