Go function, package (B)

#### Go function, including (b) 
*** Baizhang peaks, such as loose waves, terrain-kun, tenet of *** like
today to Friday you, you have not excited about it, anyway, I'm very excited , there are two days of freedom;
the one we learned functions and some knowledge of the bag's Go, then learn today ...
---
##### init function
for each program source file can contain an init function, which before the main function is executed, is called Go run frame;
package main

import "fmt"

func init(){
   fmt.Print("init ")
}
func main()  {
   fmt.Print("main")
}

  


Output: init main
init notes and details of the function:
1. If a file contains *** global variable definition, process init function and main function *** is performed as a global variable definition -> init function -> main function;
2. its main role is to complete some initialization
3. If the packet has a plurality of the init function, import sequence execution order, such as:
a introduced B, B C is introduced, it is executed in order to execute a C global variable definitions, init function, then perform packet B, and finally performs a packet;
main Package 

Import "FMT" 
var A = Test01 () 
FUNC the init () { 
   fmt.Println ( "the init") // execution order 2 
   fmt.Println (A) // execution order. 3 
} 
FUNC Test01 () {int 
   FMT. println ( "test01") // execution order. 1 
   return. 1 
} 
FUNC main () { 
   fmt.Println ( "main") execution order // 4 
}

  


---
##### anonymous functions
Go supports anonymous functions, anonymous functions that is not the name of the function, if one wishes to use a function, you can use an anonymous function, while the anonymous function can also be achieved multiple calls;
if the anonymous function assigned to a global variable, then this anonymous function has become a global anonymous function, valid in the effective scope of the program;

main Package 

Import "FMT" 

FUNC main () { 
   direct call when defined @ 
   SUM: = FUNC (A, B int) {int 
      return A + B 
   } (10,20) 
   fmt.Println (SUM) 
   // anonymous function assigned to a variable, the function call by the anonymous variable 
   a: FUNC = (a, B int) {int 
      return a + B 
   } 
   SUM = a (10,20) 
   fmt.Println (SUM) 
}

  


---
##### Closure
Closure is actually a reference to its overall function and a combination of environment-related
package main

import "fmt"

func add()func(int)int{
   var n int = 1
   return func(i int) int {
      n += i
      return n
   }
}
func main(){
   a := add()
   fmt.Println(a(1)) // 2
   fmt.Println(a(10)) //12
   fmt.Println(a(2)) //14
}

  


Description:
1. add is a function that returns a data type anonymous function;
2. anonymous function returns a reference to add function of the variable n, the flow returns to the anonymous function and n is formed integrally, constituting a closure;
3. It may be understood: closures is the class, method function, n is the field, and it uses a function of n, each closure;
4. Thus, when a function is called repeatedly, the total n;
package main

import (
   "fmt"
   "strings"
)

func addStr() func(str string) string {
   var base = "a"
   return func(str string) string {
      base += str
      return base
   }
}
// 判断字符串的后缀是否为指定的
func makeSuffix(suffix string) func(string) string {
   return func(s string) string {
      if !strings.HasSuffix(s,suffix) {
         return s + suffix
      }
      return s
   }
}
func main(){
   a := addStr()
   fmt.Println(a("b")) // ab
   fmt.Println(a("c")) // abc
   fmt.Println(a("d")) // abcd
   jpg := makeSuffix(".jpg")
   png := makeSuffix(".png")
   fmt.Println(jpg("a.jpg")) // a.jpg
   fmt.Println(jpg("b"))  //b.jpg
   fmt.Println(png("a.png"))  // a.png
   fmt.Println(png("b"))  //b.png 
}

  


1. Return suffix anonymous function and parameter variables into a closure, and therefore one can pass a plurality of times call;
---
##### defer function
defer also known to delay execution;
when the function to defer, temporarily performed, the statement after the press-fitting defer separate stack when the function is finished, before the return, then the defer the execution principles of the first embodiment according to the stack;
main Package 

Import "FMT" 

FUNC the Add (A, B int) {int 
   the defer fmt.Println ( "= A", A) 10 // output order 3, when the statement is placed on the stack, the parameter values will be related to the copy 
   defer fmt.Println ( "b =", b) // 20 output order 2, when the statement is placed on the stack, the parameter values will be related to the copy 
   a =. 11 
   SUM: = a + B 
   the defer fmt.Println ( "SUM = ", sum) // 31 sequentially output. 1 
   return SUM 
} 
FUNC main () { 
   SUM: = the Add (10,20) 
   fmt.Println (SUM) 31 is the output order // 4 
}

  


*** In defer when the statement into the stack, the value of the relevant parameters will be copied ***
1. often used defer file.Close after creating resources (open files, connect to databases, lock resource) development in Go () conn.Close ()
2. after defer, can continue to use the resources that have been created;
---
##### function parameter passing
one has talked about the value types and reference to the function parameter type, let us summarize depth, this knowledge is important in a compiled language;
1. function parameters are passed by value is a value type, function parameter is a reference type is passed by reference;
2. whether it is passed by value or reference semantics, and passed to the copy of the function is variable, except that the value passed is the value of the copy, the copy address is passed by reference;
high copy address 3. under normal circumstances the efficiency, and copies the value, the greater the size of the parameter data by the data, the efficiency of the low;
4. value type: series of basic data types int, float series, bool, string, array, structure;
5. reference types: pointer, slice sections, map, chan, interface;
main Package 

Import "FMT" 

// value passed 
FUNC Test01 (int A) { 
   fmt.Printf ( "[Test01] A = address value DA =% P% \ n-", A, A &) 
} 
// transmitted to want to change the value of the original value may be passed address variable 
FUNC TEST03 (a int *) { 
   * a = 100 
   fmt.Printf ( "[TEST03] = C% VC address value P =% \ n-", * a, & a) 
} 
// references transfer 
FUNC Test02 (A [] int) { 
   fmt.Printf ( "[Test02] B = address value VB =% P% \ n-", A, A &) 
} 
FUNC main () { 
   var A = int 10 
   fmt.Printf ( "A% = DA address value P =% \ n-", A, A &) 
   Test01 (A) 
   var B = [] {1,2} int 
   fmt.Printf ( "% B = VB address value P =% \ n-" , B, & B) 
   Test02 (B) 
   var C = 10
   test03(&c)
   fmt.Printf("c value=%v c address=%p\n",c,&c)
}

  


---
scope ##### variables
1. The function declaration or definition of internal variables are local, internal functions scoped;
2. external function declaration or definition are global variables, the whole package is valid scope when the first letter capitalized, the scope of the whole process;
3. If the variable declared or defined within the code block, such as: the if / for block, the scope is limited to the block;
main Package 

Import "FMT" 

// global variable 
var name = "golang" 
// If capitalized, is valid in the whole procedure, other packages may be used 
var Age = 22 is 

FUNC Test01 () { 
   // local variable 
   var a 10 = int 
   fmt.Println (a) 
   // use global variables 
   fmt.Println (name) 
   if a> 2 { 
      // local variables inside the block, only valid if block 
      var = int D 100 
      fmt.Println (D ) 
   } 
   // local variables inside the block, only valid if block 
   //fmt.Println(d) // error 
} 
FUNC main () { 
   // local variable 
   var B = int. 1 
   fmt.Println (B) 
   / / global variables 
   fmt.Println (name) 
   Test01 () 
}

  There are personal micro-channel public number Latest Articles: Welcome to the concern with learning exchange

Guess you like

Origin www.cnblogs.com/Mail-maomao/p/11411767.html