Golang study Excerpt

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

Golang study Excerpt

  1. Learn C,python, or Java and other languages to learn Golang should be stress-free, look at the grammar can be written. The syntax is more special as follows:

    • Declare variables and assign values using : =

      A, B: = 1, 2//declare variable B, and assign a value of

      A = 2//a assignment 2

    • If you do not need parentheses, and you can execute an expression. For statements similar to

      if x:=1; x<2 {

      }

    • The string () function < the ToString () with Java, which is the "%s" operation on the object, will result in an infinite recursive call. Because "%s" calls string (), the object is converted to a string form.

      Type MyString string

      Func (M MyString) string () string {

          return fmt.Sprintf("MyString=%s", m) // Error: will recur forever.    string(m)) // OK: note conversion.

      }

      String (m) converts m to a string object, and then "%s" is acting on the string object, not m itself, so it does not return an infinite recursion

  2. Defer a bit of a finally taste, but there are different

     for I: = 0; i < 5; i++ {defer fmt. Printf ("%d", I)} 

    Deferred functions is executed in LIFO LIFO < stack; order, so the code will C Ause 4 3 2 1 0

     func trace (s string) string {fmt. Println ("Entering:", s) return s}func un (s string) {Fmt. Println ("Leaving:", s)}func a () {Defer un (trace ("a")) FMT. Println ("in a")}func B () {Defer un (trace ("B")) FMT.  Println ("in B") A ()}func main () {B ()} 

    The arguments to the deferred function (which include the receiver if The function is a method) was evaluated when the defer executes , not when the call executes.

    When the

    defer statement executes, all parameters required by the function being defer are evaluated immediately, rather than waiting for the function to be executed by the defer to evaluate the function's parameters . The results are as follows

     entering:bin bentering:ain aleaving:aleaving:b 
  3. New and make

    New (t) returns a pointer to a newly allocated zero value of type T. New is suitable for initializing a 0 value object, new (File) and &file{} are equivalent. New ([]int) returns a pointer to a newly allocated, zeroed slice structure, which is, a pointer to a nil slice value.

    Make (T, args) creates slices, maps, and channelsonly, and it returns a initialized (not zeroed) value of type T (Not *t)

  4. Arrays

    Arrays is values. Assigning one array to another copies all the elements. array is not a reference, is a value, array A is assigned to B, copied directly to another B, the result is an array, a, a, independent, the same content

    In particular, if you pass an array to a function, it would receive a copy of the array, not a pointer to it. Array as a parameter, passing a copy of the value of the entire array, not the pointer

    The above two points are different from C language, each copy array is expensive, if you want to like C language, you can pass pointers.

  5. Slices

    The slices behavior is consistent with the array of C, which is pointer passing. Slices are more commonly used. Slices the bottom is an array, as long as the capacity of the underlying array is not exceeded, the slices address remains unchanged. Once an element is added that exceeds the capacity of the underlying array, it is reallocated reassigned. The default underlying array capacity is cap (slice).

  6. Special syntax ... (ellipsis of three points)

    x: = []int{1,2,3}

    Y: = []int{4,5,6}

    x = Append (x, y...) Remove... Error because Y is not of type int

    Fmt. PRINTLN (x)//somewhat similar to Python for dictionary **dict

  7. init function

    Each source code file can have an init function that executes after the import statement of the source code file is executed, and the variable calls its initializers after the INIT function is executed. Typically used to check whether the various states in the file are correct

  8. Import for side effect

    Sometimes import a library, not to use a function or class, just want the library's init function to execute once, do the preparatory work:

    Import _ "Net/http/pprof"//during its init function, the NET/HTTP/PPROF package registers HTTP handlers that provide debug Ging Information
  9. The
  10. Channel

    Pipeline is commonly used for communication between goroutine, and go does not recommend the use of shared memory, mutexes, and other means of communication. Pipeline for Goroutine Synchronization example:

     c: = make (chan int)//Initialize a pipe with no cache go func () {list. Sort () C <-1//Send a signal; Value does not matter.} ()///A new goroutine, to do the sort, after sorting to the pipeline to write Data dosomethingforawhile () <-c//blocking waits for the pipeline to have data written, that is, waiting for the above goroutine sort to complete 

    A pipe is used as a semaphore (semaphore), such as a current limit, example:

     var sem = make (chan int, +) func Serve (Queue Chan *request) {for req: = Range Queue {    TMP: = req//Create new instance of req for every goroutine. SEM <-1//Signal full-time write blocking go func () {process (TMP) <-SEM//Processing a request to release a semaphore} ()} 

    Because the pipeline Sem assigned b Uffer,size is 100. So the first 100 requests, can not block immediately get executed. Subsequent requests must be queued for the first 100 requests, with the request processed (the data in the pipeline being read out) to be written to the pipeline and processed. So, in this example, the pipeline acts as a limiting function: the number of requests in parallel processing must not exceed

  11. Panic recover

    Go exception handling mechanism, with try...except ...

    Because recover returns nil unless called directly from a deferred function, deferred code can call Librar Y routines that themselves use panic and recover without failing.

    Func Safelydo (Work *work) {defer func () {    If err: = Recover (); Err! = nil {        log. Println ("Work failed:", err)    }} () does (work)}

    The DO function has a panic exception, and the deferred function Func,func function is executed, and the recover catch exception is called.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.