An overview of the
We will use several sections to learn the basics of Go. The structure of this article is as follows:
Function - multi-value return - namable result parameter -DeferCopy the code
function
The basic statement structure of the function:
func DoSome(a int ) string{
return "do"
}
Copy the code
- Func is the keyword that indicates the beginning of the function.
- Arguments are written with the variable name first and the type second.
- The return value is written after the parentheses of the function’s arguments. In the above example, the return value is string
More value is returned
Functions and methods can return multiple values:
func Write(b []byte) (int, error)
Copy the code
The return values above are declared to be int and error. This is useful in cases where error messages need to be returned.
When called, you can use: r,e := Write() To ignore the second argument: r,_ := Write() to use a blank identifier.
A namable result parameter
The return value of a function can be named and used as a regular variable, just like the parameter passed in. Such as:
func nextInt(b []byte, pos int) (value, nextPos int) {
Copy the code
Once the function is named, they are initialized to a zero value corresponding to their type;
If the function executes a return statement with no arguments, the current value of the resulting parameter is returned.
An example:
func ReadFull(r Reader, buf []byte) (n int, err error) {
for len(buf) > 0 && err == nil {
var nr int
nr, err = r.Read(buf)
n += nr
buf = buf[nr:]
}
return
}
Copy the code
Defer
The defer statement is used to anticipate that a function has been called. It can also be understood as delaying the execution of a function. The function that deferred will “execute immediately” before the function to which it deferred is executed returns.
For example, a function that must release resources no matter which path it returns. A typical example would be to close a file:
func Contents(filename string) (string, error) { f, err := os.Open(filename) if err ! = nil {return "", err} defer f.close () // f.close will run after we finish.Copy the code
END