This is a creation in Article, where the information may have evolved or changed.
function declaration
funcintstringint ) { 函数体 return 语句}
- Func keyword
- (P myType) indicates the type object to which the function belongs! , that is, to define a method for a particular type , you can omit the non-write, that is, the normal function (here we mainly explain the normal function)
- Name of function
- Parameter (can not be declared)
- return value (can not be declared)
- function body
Function call
We know that there are private,public,friend in C + + classes that can control the visibility of class members. and to reduce naming conflicts through namespaces. So is java.
In the Go language python
, it is also used package
to divide different modules.
- 13 built-in functions can be called directly (all lowercase names of functions)
- Invoke a function in the standard package (directly into the standard package
import fmt
, called directly through the package name )
- Call a custom function in the same package as the keynote function (call it directly without the package name prefix)
- The called function is provided by the user-created package ! (go install generate. A file , import package name, call through package name )
The 2nd and 4th are all from the outer package, and the first letter of the function name is the uppercase letter , the difference is that the standard package has go provided, and the user created the package by the user himself.
import"pcakageName"packageName.FunctionName(参数)
In the third case, because the function is dropped and the keynote function is in the same package, it can be called directly, without importing the package name , and the first letter of the function may be lowercase (here, even if two two functions are not in the same file, as long as they are in the same package).
Calling standard functions
Golang provides a large number of packages and utility functions for use by users, and these functions are called standard functions. Common standard packages have fmt, math, os, time bytes
generic package names that are lowercase. 、
Standard package messages can be viewed under the pkg of the Go installation directory, or can be viewed using Godoc.
- Before using a function, first, import the package name
- Calling a function through the package name
Calling a custom function
Typically, an executable go program typically has a main package , which must declare a main function in the main package.
Functions that call external packages
If you need to call a function of an external package, you need to import the package to call the related function (the first letter must be capitalized).
such as building mymath
packages:
1. First establish the Mymath.go source file: Define four functions (this source file must be under the directory $GOPAHT/src/mymath)
PackageMyMathfuncAdd (A, Bint)int{return(A + b)}funcSub (A, Bint)int{return(A-B)}funcMult (A, Bint)int{return(A * b)}funcDiv (A, Bint)int{ifB! =0{return float32(a)/float32(b)}Else{return0}}
go install mypath
, the $GOPAHT/src/mymath
source files will be compiled below and installed to the $GOPATH/src/pkg/(体系结构名)/
following
After importing this package, you can call these functions directly. The package will be found under the appropriate system, and the functions in these packages can be found. ( go build
and go install
What is the difference?) )
Calling built-in functions
13 built-in functions, these built-in functions, are very useful.
len()
: Can get array, string, length of slice
panic()
Can be directly applied to the bottom of the system for error handling.
Parameter passing
Parameters are passed primarily to pass data between functions.
In the Go language, a function parameter can make a value type, or it can be a reference type. A value type is a copy of a parameter when it is passed as a function parameter. A reference type is a copy of an address. It is roughly divided into the following types:
General Delivery
Pointer passing
Array elements as parameters
array name as a parameter (the whole array will be copied)
package main import ( "FMT" ) func Main () {var b = [5 ]int {1 , 2 , 3 , 4 , 5 } f4 (b) fmt. Println (B[0 ])}func f4 (a [5 ] int ) {A[0 ] += 1 fmt. Println (A[0 ]) //does not affect the original array. Because passing the array name means copying }
When using the array name as a parameter, the argument type and the formal parameter type must be the same. For example, if the type of argument B is [5]int, then the type of the formal parameter should also be [5]int. Defining a formal parameter as []int, [10]int, and so on are all wrong, and the C language is often allowed to do so.
The Go language is type-safe, [5]int and []int], [10]int with different types of demos. If your function's return value type is defined as float32, then if you return an int type variable in the function, it will not pass. (The Go language is type-safe)
Slice as a function parameter
- This is an address copy that assigns the address of the underlying array to the slice of the parameter
- operation on the slice element, even for the underlying array.
function as a parameter pass
A function is also a data type that can assign a function to a variable.
func main(){ varint = 3, 4 f := sum f1(a, b, f)}funcintfunc(int ,intintint { fmt.Println(sum(a, b))}funcintint { return (a+b)}
return value
Return value: allows multiple return values , and allows the definition of a return value variable , so that the return statement can be more convenient.
funcint) (int ,float32){ //多个返回值 需要一个括号 returnfloat32float32(b)}
The return value can also be ignored when the function is called.
func main() { ret, _ := f2(3, 6) //可以忽略返回值}funcint) (int ,float32){ returnfloat32float32(b)}
You can name the return value parameter so that when you return, you do not have to write the return value directly.
func main() { sum, sub = f3(3, 6) fmt.Println(sum, sub)}funcintint//直接命名了返回值参数,需要一个括号 sum = a + b sub = a - b return}
Variable parameter function
The type and number of formal parameters can vary.
The typical parameter functions are: FMT. Printf (), FMT. SCANF () Exec.command (), etc.
Declaration of a variable parameter function
func functionName (variableArgumetName ... dataType) returnValue {...}
The type of the
(1) argument is "... Type, and the argument must be the last parameter of the function. If the function has other parameters, such as before the variable parameter. func F1 (a int, s string, args ... int) {...}
The
(2) variable parameter, which is actually a slice, can be traversed using range.
package mainimport"fmt"func main() { f1(1, 2, 3) f1(4, 5, 6, 7)}func f1(args ...int) { fmt.Println(args)}输出为:[1 2 3][4 5 6 7]
The transfer of variable parameter function
A variable parameter function, how to pass these arguments to another variable parameter function?
Because the argument is actually a slice, it can be passed all or partially.
package mainimport"fmt"func main() { f2(1, 2, 3) f2(4, 5, 6, 7)}func f1(args ...int) { fmt.Println(args)}func f2(args ...int) { f1(args...) f1(args[2:]...)}
The variable parameter is passed in the argument is even though it is a Slice, but with a direct transfer of a Slice is still different: variable length parameter in passing a Slice, it is simply to get a copy of Slice , the copy operation , it does not change the value of the original slice.
Any type of variable parameter function
When the user wants to pass different types of parameters, it is like FMT. Printf () can accept various types such as int string.
At this point, you should specify that the argument type is an empty interface interface{}
funcinterface{}) //指定变参类型为 interface{}
In the Go language, interface{} can point to any data type , so you can use interface{} to define any type of variable parameter. at the same time interface{] is also type-safe . (Abstract for all data types ...) It? )
PackageMainImport("FMT")funcMain () {F1(2,"Go",8,"Language",' A ',false,"A",3.24)}//using interface {} as a typefuncF1 (args ...Interface{}) {varnum = Make([]int,0,6)varstr = Make([]string,0,6)varCH = Make([]Int32,0,6)//character type, is Int32 's Oh! varother = Make([]Interface{},0,6)//Using interface{} as the type for_, arg: =Rangeargs {SwitchV: = Arg. (type) {//What is this usage? Case int: num =Append(Num, V) Case string: str =Append(str, v) Case Int32://Here ' a ' is counted into the Int32. CH =Append(CH, v)default: other =Append(Other, V)} } FMT. PRINTLN (num) fmt. Println (str) FMT. PRINTLN (CH) fmt. Println (Other)} output is:[28][GoLanguage A][][false3.24]
You can see that the Go language is type-safe. int
types int32
are not the same type, but should be compatible. Character literals are treated rune
as types (i.e. int32
, type, but not int
type)
anonymous functions
Statement:
func (参数列表)(返回值){函数体} //注意没有函数名,所以称为匿名函数funcintint { return (a + b)}
- You can define an anonymous function in your code at any time, and assign the anonymous function to a variable.
- You can define an anonymous function at any time and execute the anonymous function. (When declaring a function, execute it directly!) )
package mainimport ( "FMT" ) func Main () {//declares and assigns the anonymous function directly to the variable F f: = func (A, b int ) int {return A + b} //calls to variables of the function type sum: = F (2 , 3 ) fmt. Println (sum) //declares and executes the anonymous function directly sum = func (A, B int ) int {return A + b} (2 , 3 ) fmt. Println (SUM)}
Note: Using an anonymous function, you cannot use it as a top-level function , which means you must place it in the function body of other functions.
2. Variables in the parent function can be used directly in an anonymous function (which is also a handy use)
function closures
Closure
Defer statements
- The defer statement registers with the function.
- Executes when the function exits (whether the function is panic () or exits normally)
- Defer registration statement follows the order of "register first, then execute"
- You can use the defer statement to do some resource cleanup work.
Golang Abnormal recovery mechanism
The abnormal recovery mechanism of Golang is a mechanism using panic ()/Recover ().
These are built-in functions.