课程: Go Practice: Functions

Introduction to functions - Go教程

课程: Go Practice: Functions

Introduction to functions

- [Instructor] Before you start the first challenge, let's go over some of the fundamentals of Go functions. This refresher will be useful to you if you're getting started with Go or don't write it on a regular basis. Functions are central to Go. They're easily declared using the func keyword followed by the function name. They can take zero or more parameters and return zero or more values. Unlike other languages, values must be explicitly returned using the return statement in Go. In this example, the myFunc function is being declared, then it's taking in two parameters and returning two values. Go provides easy support to integrate functions with its custom types called structs. Methods are declared using a special method receiver type which is declared in round brackets between the func keyword and the name of the method. Just remember that a pointer receiver type is required if you want to prevent the receiver instance from being copied or if the method is making changes to it. In this example, we declare a struct type, which has a myFunc method. We'll invoke this method later, like in a main function by initializing an instance of myStruct and invoking the myFunc method on it. Let's get some hands-on practice by implementing a function which calculates the mean of a slice of numbers, given a slice X of length N, the mean is the sum of all numbers in the series divided by n. I have written the formula out in pseudo code for you for easier reference. I've written the boilerplate code for you to save you some time. On line 14, I've already defined the calculate mean function which takes in a number slice as a parameter and returns a pointer to float 64 and an error. This method is not implemented, so it returns nil and an error with the not implemented error message. This function should return nil and an error with the empty numbers message in the case that the number slice is empty. Your challenge is to implement the calculate mean function. This exercise should take you no longer than 15 minutes. Then you can join me in the next video to see my solution. Good luck.

内容