Go notes-functions

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Function

The core design inside the go language, declared by the keyword func

Func funcName (Input type1, Input2 type2) (output1 type1, Output2 type2) {    //logical code    return value1, value2}

Basic syntax

1. Syntax

General function Func Func_name (a int) {    println (a)}//multi-parameter, no return value func Func_name (A, B int, c string) {    println (A, B, c)}//single return value F UNC Func_name (A, b int) int {//the same type, can omit  a, b int    return a + b}//multiple return values func Func_name (A, b int) (c int, err error) {  //return value can also be   (int, error)    return a+b, Nil}func sumandproduct (A, b int) (int, int) {    return a+b, a*b}

2. Description:

The keyword Func declaration can have one or more parameters, followed by a type after each parameter, through the "," separator function can return more than one value return value declaration, can only declare the type    if there is no return value, you can omit the last return information    if there is a return value, The Returngo function that must be added in the outer layer does not support nesting (nested), overloading (overload), and default parameters (defaults parameters) Support:    1. No need to declare prototypes    2. Variable length parameter    3. Multiple return values    4. Name the return value parameter    5. anonymous function    6. Closure Note:    The function starts with Func, and the opening brace cannot be another line

A function that starts with a lowercase letter is visible in this package, and a function that starts with a capital letter can be called by another package

Multiple return values and named return parameters

Can return multiple results like Python, except for non-tuple

For unwanted return values, you can throw garbage cans _

If you return a parameter with a name, the return statement can be empty. Return is not NULL, the order of returned values is the order of return rather than the order in which the function header is declared

Package MainFunc Change (a, b int) (x, y int) {    x = a +    y = B +    return   //101, 102    //return X, y  //Ibid.    //return y, x  //102, 101}func Main () {    A: = 1    B: = 2    c, D: = Change (A, b)    Prin TLN (c, D)

If a named return parameter is overridden by a variable of the same name in a code block, you must return the result using an explicit return

You do not need to force a named return value, but a named return value can make the code clearer and more readable

Parameter passing: Passing values and passing pointers

Pointer, go reserved pointer, with "." Instead of the "--" action pointer, the target object member operator

& Take variable address * Indirect access to target function via pointer func add1 (a int) int {    A = a + 1    return a}x: = 3x1: = ADD1 (x) x//3x1//4 pass value, x1 value does not change func a DD2 (a *int) int {    *a = *a + 1    return *a}x: = 3x1: = ADD2 (&x) x//4x1//4

Pass pointer multiple functions can manipulate the same object

The pointer is relatively lightweight (8byte), just pass the memory address, I am hungry can use the pointer to pass the large volume structure body

In the go language, string,slice,map these three types of implementations are similar to pointers, so they can be passed directly without having to take the address and pass the pointer

Note that if the function needs to change the slice length, it still needs to fetch the address pointer

Parameter passing: variable parameter

A parameter is essentially a slice and must be the last parameter

When passing slice to a variable parameter function, pay attention to the use of ... unfold, otherwise it will be treated as a dang single parameter, similar to Python

Package MainFunc sum (s string, args ... int)  {    var x int    for _, N: = range args {        x + = n    }    println ( s, x)}func main () {   sum ("1+2+3=", 1, 2, 3)   x: = []int{0,1,2,3,4}   sum ("0+1+2+3=", X[:4] ...)} ... type types can only exist as parameter types of a function, and the last parameter is essentially an array slice, i.e. []type

Indefinite parameters of any type

Func Printf (format string, args ... interface{}) {}

anonymous functions

F: = func (x, y int) int {    return x + y}

function as value, type

In the go language, a function is also a variable that can be defined by type, which is the same as all parameters with the same return value.

Syntax Type typeName func (input1 inputType1, Input2 inputType2 [, ....]) (Result1 resultType1 [,....])

Usage E.g.1

Type testint func (int) bool//declares a function type func filter (slice []int, F testint) []int {    var result []int    for _, Value: = Range Slice {        if f (value) {            result = Append (result, value)        }    }}func isodd (integer int) bool {    if int Eger% 2 = = 0 {        return false    }    return True}filter (A, isodd)

This usage is very useful when writing interfaces.

Usage e.g.2

You can define a function type, or you can pass a function as a value (default value nil)

Package main//defines a function type Callbacktype callback func (S string)//defines a function that can receive another function as parameter//sum as parameter name, func (int, int) int as parameter type func Test (A, b int, sum func (int, int) int)  {    println (sum (b))}func main () {    //demo 1    var cb callback    cb = f UNC (s string) {        println (s)    }    cb ("Hello World")    //Demo 2    Test (1, 2, func (A, b int) int {return a + B})}

Results:

Hello world3

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.