Go commonly used functions

#### Go commonly used functions, error handling 
In this section we learn about Go to commonly used functions, some of these functions are built-in, standard library of some official, familiar with these functions is very important in terms of program development;
byte length 1. len ( "abc") of the string statistics
fmt.Println (len ( "abc, me")) // 4 + 3 = 7 Chinese characters occupy three bytes

  


2. strconv.Atoi ( "11") the string to an integer
    STR = var ". 11" 
   S, ERR: = strconv.Atoi (STR) 
   fmt.Println (S, ERR) // nil. 11, the default if no error, returns nil

  


3. strconv.Itoa (11) into a string integer
    A =. 11 var 
   S: = strconv.Itoa (A) 
   fmt.Println (S) //. 11, by default, returns an empty string if the conversion is not successful

  


4. strconv.FormatInt (11,2) type int64 integer into a string of 8, 16 hex
   var a int64 = 11
   fmt.Println(strconv.FormatInt(a,10)) // 11
   fmt.Println(strconv.FormatInt(a,2)) // 1011
   fmt.Println(strconv.FormatInt(a,8)) // 13
   fmt.Println(strconv.FormatInt(a,16)) // b 

  


5. [] byte ( "abc") byte string into sections
    var a = "abc"
   fmt.Println([]byte(a)) // [97 98 99] 

  


6. The String [] rune ( "Hello") comprising Chinese or other languages ​​into byte slice rune
    var a = "hello" 
       fmt.Println ([] Rune (A)) // [20320 22909] Unicode encoding

  


7. strings.Contains ( "abc", "a") comprises determining whether the target character string
    fmt.Println(strings.Contains("abc","a")) // true

  


Number 8. strings.Count ( "abc", "a") target character string appearing statistics
    fmt.Println(strings.Count("abaac","a")) // 3

  


9. strings.EqualFold ( "abc", "ABC") is not case-sensitive string comparison
    fmt.Println(strings.EqualFold("abc","ABC")) // true

  


10. strings.Index Index ( "aabbcc", "a") query target character string in the first occurrence (index) value
    fmt.Println(strings.Index("aabbcc","a")) // 0

  


11. strings.LastIndex Index ( "aabbcc", "a") query target character string last occurrence (index) value
    fmt.Println(strings.LastIndex("aabbcc","a")) // 1

  


12. strings.Replace ( "aabbcc", "a", "d", - 1) The specified string with another string may specify an alternative number
    // -1 means replacing all the target characters 
    fmt.Println (strings.Replace ( "aabbcc", "a", "d", - 1)) // ddbbcc

  


13. strings.Split ( "aa, bb, cc", ",") to convert the string specified by the character string into a slice *** ***
    fmt.Println(strings.Split("aa,bb,cc",",")) // [aa bb cc]

  


14. strings.ToUpper ( "aa") string to uppercase
    fmt.Println(strings.ToUpper("aa")) // AA

  


15. strings.ToLower ( "AA") string lowercase
    fmt.Println(strings.ToUpper("AA")) // aa

  


16. strings.TrimSpace ( "aa bb cc") of the string left and right spaces removed
    fmt.Println(strings.TrimSpace(" aa bb cc ")) // aa bb cc

  


17. strings.Trim ( ", aa, bb, cc,", ",") the left and right sides of the specified character string is removed
    fmt.Println(strings.Trim(",aa,bb,cc,",",")) // aa,bb,cc

  


18. strings.TrimLeft ( ", aa, bb, cc,", ",") to the left of the designated character string is removed
    fmt.Println(strings.TrimLeft(",aa,bb,cc,",",")) // aa,bb,cc,

  


19. strings.TrimRight ( ", aa, bb, cc,", ",") to the right of the specified string of characters removed
    fmt.Println(strings.TrimRight(",aa,bb,cc,",",")) // ,aa,bb,cc

  


20. strings.HasPrefix ( "http://127.0.0.1", "http") determines whether the specified character string beginning
    fmt.Println(strings.HasPrefix("http://127.0.0.1","http")) // true

  


Whether 21. strings.HasSuffix ( "abc.jpg", "jpg") determines the end of the specified character string
    fmt.Println(strings.HasSuffix("abc.jpg","jpg")) // true

  


---
##### and date-related time functions of
time and date functions related to the need to import time packet
type time is: time.time
time constant:
const ( 
   Nanosecond the Duration =. 1 // ns 
   Microsecond = 1000 * Nanosecond // sec 
   Millisecond = 1000 * Microsecond // ms 
   Second = 1000 * Millisecond // sec 
   Minute = 60 * Second // sub 
   Hour = 60 * Minute // hours 
)

  

 
main Package 

Import ( 
   "FMT" 
   "Math" 
   "Time" 
) 

FUNC main () { 
   now: = Time.now () 
   fmt.Printf ( "% V now IS value, now IS type T% \ n-", now, now ) 
   // get to a specific time 
   fmt.Println (now.Year ()) // in 
   fmt.Println (now.Month ()) // May 
   fmt.Println (now.Day ()) // day 
   fmt.Println (now.Hour ()) // when 
   fmt.Println (now.Minute ()) // sub 
   fmt.Println (now.Second ()) // second 
   fmt.Println (now.Date ()) // date 
   / / date format 
   @ 2006-01-02 15:04:05 six number is fixed, to be written, the position can be altered, where 15, 03 can also be written, representing 24 and 12-hour  
   fmt .Println (now.Format ( "2006-01-02 15:04:05" ))
   fmt .Println (now.Unix ()) // from 1970-01-01 to now elapsed time: seconds
   fmt.Println (now.UnixNano ()) // from 1970-01-01 to now elapsed time: ns, if more than int64 range indicated, the result will overflow 
   fmt.Println (math.MaxInt64) // int64 can the maximum range indicated 
}

  


---
###### built-in functions
provided in Go some functions that can be used directly, known as built-in function
1. len: Test for rectification, such as: string, array, slice, map , channel;
2. new: mainly used to allocate memory to assign a value type, such as: int, float64, struct, etc., returns a pointer to a corresponding value type;
3. the make: to allocate memory, mainly used to assign a reference type, such as:. Channel, the Map, Slice
4. the role of the make, learning to learn in detail again later when the complex data types, here to learn about usage
main Package 

Import "FMT" 
FUNC main () { 
   var * int // define a variable of type a * int, int type pointer to 
   a = new (int) // used to allocate new memory 
   fmt.Printf ( "a value is% p \ n "value of a, a) // variables, is actually a new step out address: 0xc000010098 
   fmt.Printf (" address a is% p \ n ", & a) // the address of a variable, a variable address their own: 0xc000006028 
   * a = 100 // address points to a value of 100 
   fmt.Println (* a) 
   // compare traditional variable declarations 
   var b int 
   b = 100 
   fmt.Printf ( "b value % D IS \ n-", B) 
   fmt.Printf (" address B P IS% \ n-", & B) 
   // a new way 
   // A -> 0xc000010098 -> 100 
   // ordinary manner 
   // b - -> 100 
   // 
   // the make  
   var C [] int
   C = the make ([] int,1) // a reference type c (sliced), allocating memory, if you do not allocate memory (declaratively) are not used 
   // re-emphasize here several variables declaratively 
   / type / 1. display declare a variable, then the assignment, var b int, b = 100 ; cited in this way must declare the types of variables make, or can not use variables 
   // 2. directly assign values to variables, the compiler infer variable type, var b = 100; in this way a reference type variable declaration must make, can not be used otherwise the variable 
   // 3. short variable declarations, only for internal function, B: 100 = 
   C [. 1] = 10 
   FMT .Println (C) 
}

  


---
##### Error handling
1. By default, the program panic when an error occurs, the program will quit;
2. In fact, some errors do not need to exit, in order to ensure the normal operation of the program, we can catch the error, and error handling;
3. Go does not support traditional try ... catch ... finally this syntax, it's the wrong way to capture the process: defer panic, recover;
main Package 

Import "FMT" 

FUNC Test01 () { 
   // defer recover to capture the error using 
   the defer FUNC () { 
      R & lt: = Recover () 
      ! = nil {IF R & lt 
         fmt.Println ( "capture error, need to handle") 
         FMT .Println (R & lt) 
      } 
   } () 
   A: = 10 
   var int B 
   RES: = A / B // divisor is not 0, the program can cause panic this place, i.e. collapse, after adding error handling procedures can ensure normal run 
   // If there is no program to defer recover here withdrew;   
   fmt.Println (RES) 

} 
FUNC main () { 
   test01 () 
   fmt.Println ( "after the error handling, but also operating normally") 
}

  


---
##### custom error
custom errors and packet errors need to panic function;
errors.New ( "String") returns the value of a type of error indicates an error
panic is a built-in function, receiving a the interface value (any value may be received), output an error message and exits the program;
package main

import (
   "errors"
   "fmt"
)

func test01()(err error){
   defer func() {
      r := recover()
      if r != nil {
         // 自定义错误
         err = errors.New("something is wrong")
         return
      }
   }()
   var a = 10
   var b int
   res := a / b
   fmt.Println(res)
   return nil
}
func main()  {
   err := test01()
   if err != nil {
      panic("test01 is wrong") // 报出错误,并退出程序
   }
   fmt.Println("main is running")
}

  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/11411793.html