课程: Practice It: Go REST API Server

Methods vs. functions

- [Presenter] Methods versus functions is the age old question. Let's break down a difference and Go. Functions are blocks of code grouped together to perform a specific task. Grouping the code into a function allows the code to be executed repeatedly. Functions only get executed when called. Now, we have already created some functions, but let's break down the syntax. We use the key word func, then the function name. If not main, which must exist in an application, you can name your function anything that isn't a keyword and Go. The convention is a word or words in CamelCase. Try for a name that best describes what the function is doing as succinctly as possible. So, in this case, we'll use an example, volume. Next, the parenthesis. If there are no parameters or input values, then just empty paramts. But if there are parameters, then you must name the argument and state the argument type. If you have multiple parameters of the same type, you can use shorthand. For example, I have function volume and it's Going to take a length, a width, and height and they will all be int. Next is the return type, if there is one. And in my example, the return type will be int. Then the curly brackets. Inside of these will be the code to accomplish the task. In this case, calculating the volume. So, in the brackets we will add the line, return, length, times width, times height. You can also have multiple return values unlike other programming languages. Where in order to do this, you would have to return an object. In Go though, you specify the return types surrounded by parentheses. So, we could have int slash int. You can also name them. So, if we were to change the volume function to dimensions and change the return type to area, which will be in int and volume, which will also be in int, we will add the line, area equals length times width, and we will change this line to be volume equals. And then, the return keyword, you don't have to explicitly add area and volume to the return line since these are already named return values. So, if we were to do them in main, it would be area comma volume equals dimensions. And then, we can print it out. We'll add area volume. Now having defined functions, how do they compare to methods? Well, Go methods are functions with a receiver argument. What are receiver arguments? I cover that next.

内容