课程: Go Practice: Functions

Solution: Introduction to functions - Go教程

课程: Go Practice: Functions

Solution: Introduction to functions

- [Isn't] Here's my implementation of the CalculateMean function according to the established function signature. On lines 16 to 18, I used an IF statement to check whether the number slice is nil or empty. This is an error case for the mean because we can't divide by zero, which is required by the mean formula. Inside the IF statement, I return nil and create a new error using the errors package. The new function takes in the message empty numbers. As is typical with idiomatic Go, the error case is handled first in the function. Next, I declare a variable sum of type int on line 19. I will write the sum of the numbers to this variable. Now I'm ready to compute the sum of the elements. On lines 20 to 22, we use the range operator instead of a typical for loop. I discard the index using the underscore blank identifier and declare a num variable. Then I range over the number slice. We add the value of each element to the sum variable which exists outside the scope of the for loop. We can now calculate the mean. On line 23, we declare a mean variable using the colon equals shorthand operator. Then we cast the sum as a float64 and divided by the length of the number slice, which is also cast as float64. Casting the two numbers to float64 types will allow us to compute results with decimal point values. Finally, I return a pointer to the mean variable and a nil error. That's all I need to do to implement the CalculateMean function. Let's try out our function by using the Test My Code button. It works and the value is what I expected. We've successfully implemented the CalculateMean function and completed the first challenge.

内容