Go language "Seventh": Go function

Source: Internet
Author: User
Tags define local

Go language functions

A function is a basic block of code that is used to perform a task. The go language has at least one main () function, which can be used to separate functions by functions, logically each of which performs a specified task. The function declaration tells the compiler the name of the function, the return type, and the parameter. The Go Language standard library provides a variety of built-in functions that are available, such as the Len () function, which accepts different types of parameters and returns the length of that type. If the string is passed in, the length of the string is returned, and if an array is passed in, the number of elements contained in the array is returned.

function definition
The Go language function defines the following format:

func function_name( [parameter_list] ) [return_types] {    函数体}

Function definition Resolution:

    • Func: Functions are declared by fun;
    • Function_name: function name, functions name and parameter list together constitute the function signature;
    • Parameter list: parameter list, parameter is like a placeholder, when the function is called, you can pass the value to the parameter, this value is called the actual parameter. The parameter list specifies the type of parameter, the order, and the number of arguments. Parameters are optional, that is, the function can also contain no arguments.
    • Return_types: return type, function returns a series of values. Return_types is the data type of the column value, and some features do not require a return value, in which case return_types is not required.
    • function Body: A collection of code for function definitions;

code example:
The following is the code for the Max () function, which passes two shaping parameters num1 and num2, and returns the maximum values for both parameters:

/* 函数返回两个数的最大值 */funcintint {    /* 声明局部变量 */    varint        if (num1 > num2){        result = num1    }else {        result = num2    }    return result}

Function call
When you create a function, you define what the function needs to do, and perform the specified task through a function call. Call a function, pass a parameter to the function, and return a value, for example:

 PackageMainImport "FMT"funcMain () {/ * Define Local Variables * /    varAint= -    varBint= $    varRetint    / * Call the function and return the maximum value * /RET = Max (A, b) fmt. Printf ("max value:%d"\ n", ret)}/ * function returns the maximum value of two digits * /funcMax (NUM1, num2int)int{/ * Declare local variables * /    varResultint    if(Num1 > Num2) {result = NUM1}Else{result = num2}returnResult

The above example calls the Max () function in the main () function and executes the result:

最大值时:200

function returns multiple values
The GO function can return multiple values, for example:

package mainimport"fmt"funcstring) (stringstring) {    return y, x}func main(){    a, b := swap("Mahesh""Kumar")    fmt.PrintIn(a, b)}

The result of the above instance execution is:

Kumar Mahesh

function parameters
If a function uses a parameter, the variable can be called a function's formal parameter, which is a local variable as defined in the function body. Call a function, you can pass parameters in two ways:

Delivery Type Description
Value passing Value passing means that a copy of the actual parameter is passed to the function when the function is called, so that if the parameter is modified in the function, it will not affect the actual argument
Reference delivery Reference passing refers to the passing of the address of the actual parameter to the function when the function is called, and the modification of the parameter in the function will affect the actual argument

By default, the time-to-use value passed by the go language does not affect the actual parameters during the call.
function usage

function Usage Description
function as a value The function can be used as a value after the top.
Closed Package Closures are anonymous functions that can be used in dynamic programming
Method The method is a function that contains the receiver.

Value Passing Value
Passing means that a copy of the actual parameter is passed to the function when the function is called, so that if the parameters are modified in the function, the actual parameters will not be affected. By default, the go language uses value passing, which means that the actual parameters are not affected during the call, and the swap () function is defined below:

/* 定义相互交换值的函数 */funcintint {    varint         /* 保存x的值 */    /* 将y的值赋给x */    /* 将temp值赋给y */        return temp;}

Use value passing to invoke the swap () function:

 PackageMainImport "FMT"funcMain () {/ * Define Local Variables * /    varAint= -    varBint= $Fmt. Printf ("The value of the Before interchange A is:%d\ n", a) fmt. Printf ("The value of the Before interchange B is:%d\ n", b)/ * Exchange values by calling functions * /Swap (A, b) fmt. Printf ("The value of a after Exchange is:%d\ n", a) fmt. Printf ("The value after Exchange B is:%d\ n", b)}/ * Define functions for exchanging values with each other * /funcSwap (x, yint)int{varTempinttemp = X/ * Save the value of X * /x = y/ * Assign the value of y to X * /y = Temp/ * Assign the temp value to Y * /        returntemp;}

The result of the above code execution is:

100200100200

Reference pass-through value
Reference passing refers to the passing of the address of the actual parameter to the function when the function is called, and the modification of the parameter in the function will affect the actual parameter. The reference pass pointer parameter is passed to the function, and the following is the Swap function swap () using the reference pass:

/* 定义交换值函数 */func swap(x *int, y *int){    varint    /* 保持x地址上的值 */    /* 将y值赋给x */    /* 将temp值赋给y */}

The swap () function is called by using reference passing:

 PackageMainImport "FMT"funcMain () {/ * Define Local Variables * /    varAint= -    varBint= $Fmt. Printf ("pre-swap value of a:%d\ n", a) fmt. Printf ("value before Interchange B:%d\ n", b)/* Call the Swap () function* &a points to a pointer, the address of a variable* &b points to the B pointer, the address of the B variable    */Swap (&a, &b) fmt. Printf ("The value of a after Exchange:%d\ n", a) fmt. Printf ("Value after Exchange B:%d\ n", b)}funcSwap (x *int, Y *int) {varTempinttemp = *x/ * Save the value on the x address * /*x = *y/ * Assign y value to X * /*y = Temp/ * Assign the temp value to Y * /}

The result of the above code execution is:

100200200100

function as a value
The go language makes it possible to create functions flexibly and use them as values. In the following example we initialize a variable in the defined function just to use the built-in function math.sqrt (), the instance is:

package mainimport (   "fmt"   "math")func main(){   /* 声明函数变量 */   funcfloat64float64 {      return math.Sqrt(x)   }   /* 使用函数 */   fmt.Println(getSquareRoot(9))}

The result of the above code execution is:

3

Closed Package
The go language supports anonymous functions, which can be used as closures. An anonymous function is an "inline" statement or an expression. The advantage of anonymous functions is that you can directly use variables within a function, without stating. In the following example, we create the function getsequence () and return another function, which is designed to increment the I variable in the closure with the following code:

package mainimport"fmt"funcfuncint {   i:=0   returnfuncint {      i+=1     return i     }}func main(){   /* nextNumber 为一个函数,函数 i 为 0 */   nextNumber := getSequence()     /* 调用 nextNumber 函数,i 变量自增 1 并返回 */   fmt.Println(nextNumber())   fmt.Println(nextNumber())   fmt.Println(nextNumber())      /* 创建新的函数 nextNumber1,并查看结果 */   nextNumber1 := getSequence()     fmt.Println(nextNumber1())   fmt.Println(nextNumber1())}

The result of the above code execution is:

12312

function methods
There are functions and methods in the go language, one method is to include the receiver's function, the recipient can be a named type or struct type of a value or a pointer, all the methods of a given type of method data of that type, the syntax format is as follows:

func (variable_name variable_data_type) function_name() [return_type] {    /* 函数体 */}

The following defines a struct type and a method of that type:

package mainimport (   "fmt"  )/* 定义结构体 */typestruct {  float64}func main() {  var c1 Circle  10.00  fmt.Println("Area of Circle(c1) = ", c1.getArea())}//该 method 属于 Circle 类型对象中的方法funcfloat64 {  //c.radius 即为 Circle 类型对象中的属性  return3.14 * c.radius * c.radius}

The result of the above code execution is:

Area of Circle(c1) =  314

Go Language "seventh": Go function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.