Golang Learning Notes (V): function _golang

Source: Internet
Author: User
Tags anonymous define function

Function

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

Copy Code code as follows:

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

Basic Syntax

1. Grammar

Copy Code code as follows:

General functions
Func func_name (a int) {
println (a)
}

Multiple parameters, no return value
Func Func_name (A, B int, c string) {
println (A, B, c)
}

Single return value
Func Func_name (A, b int) int {//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:
Copy Code code as follows:

Keyword Func declaration
can have one or more parameters, each followed by a type, and the "," separator function can return multiple values
return value declaration, you can declare only types
If there is no return value, the last return information can be omitted
If you have a return value, you have to add it to the outer layer


The GO function does not support nesting (nested), overloading (overload), and default parameters (defaults parameters)
Support:
1. No need to declare prototypes
2. Indefinite length variable parameter
3. Multiple return value
4. Named return value parameter
5. Anonymous function
6. Closure of the package

Attention:
function begins with Func, opening brace cannot be started on another line


Functions that begin with lowercase letters are visible in this package, and functions that begin with uppercase letters can be invoked by other packages


multiple return values and named return parameters

Can return multiple results like Python, but not tuple

For unwanted return values, you can throw garbage cans _

If you use a named return argument, the returns statement can be empty. Return is not null and returns are in order rather than in the order of the function header declaration

Copy Code code as follows:

Package Main

Func Change (A, b int) (x, y int) {
x = a + 100
y = B + 100

Return//101, 102
return x, y//Ibid.
Return y, x//102, 101
}

Func Main () {
A: = 1
B: = 2
C, D: = Change (A, B)
println (c, D)

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

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

Parameter passing: Passing values and passing pointers

Pointer, go to keep the pointer, with "." Instead of the "->" Action pointer target object member operator

Copy Code code as follows:

& Take variable Address
* Indirect access to the target function via pointers

Func add1 (a int) int {
A = a + 1
Return a
}

X: = 3
X1: = ADD1 (x)
X//3
X1//4
Value is passed, the value of X1 has not changed

Func add2 (a *int) int {
*a = *a + 1
Return *a
}
X: = 3
X1: = ADD2 (&x)
X//4
X1//4

Multiple functions of a pointer can manipulate the same object

Pointer comparison lightweight (8byte), just pass the memory address, I am hungry can use the pointer to pass the volume of large structures

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 pass the pointer over the address

Note that if the function needs to change the slice length, you still need to take the address pass pointer

Parameter passing: variable parameters

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

When passing slice to a variable parameter function, pay attention to ... Expand, or it will be treated as a single parameter of dang, similar to Python

Copy Code code as follows:

Package Main

Func 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 type can exist only as a parameter type of a function and is the last parameter
is essentially an array slice, that is, []type

Indefinite parameters of any type

Copy Code code as follows:

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

Anonymous Functions
Copy Code code as follows:

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

function as a value, type

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

Grammar

Copy Code code as follows:

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

Usage E.g.1

Copy Code code as follows:

Type testint func (int) bool//Declaration of 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 integer% 2 = 0 {
return False
}
return True
}

Filter (A, isodd)

This usage is useful when writing an interface

Usage e.g.2

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

Copy Code code as follows:

Package Main

Define function Type callback
Type callback func (s string)

Defines a function that can receive another function as an argument
Sum is the parameter name, func (int, int) int is the parameter type
Func Test (A, b int, sum func (int, int) int) {
println (sum (a,b))
}

Func Main () {
Demo 1
var CB callback
CB = Func (s string) {
println (s)
}
CB ("Hello World")

Demo 2
Test (1, 2, func (A, b int) int {return a + B})
}


Results:
Copy Code code as follows:

Hello World
3

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.