Go in action-manning 2016 (reading notes)

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

Go in Action

Go in action-manning 2016

Directory

    • 1 introduction go
    • 2 go QuickStart
    • Li class= "toclevel-1 tocsection-3" > 3 packaging, tools
    • 4 arrays, slices, and maps
    • 5 go type system
    • 6 concurrency
    • 7 concurrency mode
    • 8 standard library
    • 9 Test and performance benchmarks

Introduction to Go

    1. Fmt. Println ("Hello, World")
    2. ? Does the book seem to mention go exception handling?

Go Quick Start

    1. Log. Setoutput (OS. Stdout)//import ("Log" ...)
    2. Package main//main must be in the main bundle to generate the executable file? Usually named in your directory?
      1. Func init () {...}
      2. Func main () {...}
    3. Search.go
      1. var matchers = make (Map[string]matcher)
      2. Go func (matcher matcher, feed *feed) {...} (Matcher, Feed)
    4. defer file. Close ()//followed by initialization of file, err: = OS. Open (datafile) is in the same scope, which is really a bit simpler than try-finally or using
    5. Func Match (matcher matcher, Feed *feed, searchterm string, results chan<-*result) {
      1. Note the parameter declaration of ' write Chan ' here
    6. What if the * members in the 2 value struct refer to the same object? -Will the count be automatically quoted?
    7. XMLName XML. Name ' xml: ' item '//And this type?

Packaging, tools

    1. Remote import:
      1. the import github.com/spf13/viper//go build command searches the local gopath (eh? Will this result in always downloading to the latest version? may not be compatible)
    2. name import:
      1. import (myfmt "mylib/fmt")
    3. Anonymous import (SQL driver, abbreviated)
    4. li>filename := OS. ARGS[1]
      1. contents, err := ioutil. ReadFile (filename)//Read all the contents? Don't have an iterator
    5. go build.
    6. Go vet//lint tool?
    7. Go FMT//code cleanliness ...
    8. godoc-http=:6060
    9. Dependency Management
      1. vendoring
        1. import "Bitbucket.org/ww/goautoneg" to
          • "GITHUB.A Rdanstudios.com/myproject/godeps/_workspace/src/bitbucket.org/ww/goautoneg "
      2. GB The problem with
        1. import is that no version is specified
        2. vendored code: $PROJECT/vendor/src/
        3. is incompatible with Go get
        4. GB Build All

arrays, slices, and maps

  1. Array
    1. Array: = [5]int{10, 20, 30, 40, 50}
    2. Array: = [...] INT{10, 20, 30, 40, 50}//auto-infer array length, dimension once initialized cannot be modified
    3. Array: = [5]int{1:10, 2:20}//select subscript initialization?
    4. ARRAY[2] = 35
    5. Array: = [5]*int{0:new (int), 1:new (int)}//Arrays of pointers
      1. *ARRAY[0] = 10//In fact, the go language does not strictly distinguish between pointers and references?
    6. Array1 = array2//array is a value object, the assignment causes the memory copy
    7. Array2D: = [4][2]int{{10, 11}, {20, 21}, {30, 31}, {40, 41}}
    8. Pass the address of the array to the function: Func foo (array *[1e6]int) {...}//Note that the array pointer type here is much more straightforward than the C language.
  2. Slice: Is the encapsulation of the array, addr,length,capacity metadata is provided internally
    1. slice := make ([]string, 5)
    2. slice := ma Ke ([]int, 3, 5)
    3. slice := []string{"Red", "Blue", "Green", "Yellow", "Pink"}//note here [] There are neither length constants nor ... Auto-infer
    4. newslice := Slice[1:3]//Length 2, Volume 4? Newslice Initial case Reference slice?
      1. Slice capacity =5,newslice =5-1=4, note that Newslice does not have access to slice[0] elements (This design is interesting!).
    5. Multiple slice may share a chunk of memory (so the modifications need to be synchronized)
    6. Slice[index] can only access elements within the length range, to access the capacity range, Requires Append:newslice = Append (newslice)
      1. when the underlying actual storage is below the new capacity, will append allocate new memory? A little realloc.
      2. append:length=1000 each time double, otherwise add 25%
    7. slice := Source[2:3:4]//If yes Start:length:capacity triples (not the kind of syntax in Python)
    8. iteration: For index, value := range Slice {...}//g o idiomatic method; Think of the enumerate function in Python
  3. Map
    1. Dict: = Make (Map[string]int)
    2. Dict: = map[string]string{"Red": "#da1337", "Orange": "#e95a22"}//Note,: = represents type definition (auto-inference) and initialization
    3. Dict: = map[[]string]int{}//Compile error: Slice cannot be used as a map key (must execute = = operation), but can be used as map value
    4. Nil Map question:
      1. var colors map[string]string
      2. colors["Red" = "#da1337"//Run-time error
        1. Can do this: value, exists: = colors["Blue"]//GO usage
      3. Value: = colors["Blue"]//This is OK, if key does not exist, value returns type 0 values
    5. Delete (colors, "Coral")//delete element, again built-in function, which differs from the C + + language member function style
    6. Map does not copy when passed between functions

The Go type system

  1. var always initializes the variable to a value of 0
    1. : = Simultaneous declaration and initialization
  2. Type typeName struct {fields ...}
    1. Then you can func (a typeName) methodName (args) retType {...} Extension method.
      1. It can also be written as Func (a *typename) ..., but when the method is called, it is all. number, but the pointer type variable must be &struct{...} Initialized to the
      2. A typename parameter represents a method that operates on the value type of type, which is the Const method inside C + +?
      3. A variable of type value can invoke a method defined with a pointer type (these places are too easy for a person to confuse) and will be converted to (&obj). Method ()
  3. Reference types: Slice, map, channel, interface, func
    1. ' Header ' value, contains a pointer
  4. Interfaces
    1. ' Method sets ' (vtable in C + +?) )
    2. Is the method pointer in the interface not dynamically populated at runtime???
    3. The recipient of an interface implementation is usually *t, not the value type of T?
      1. If you implement an interface with the value T type as the recipient, then the interface can accept T and *t (?) as a parameter. )
  5. Type embedding
    1. A bit Ruby/scala mixin style ~
    2. Inner type promotion//As long as the name does not conflict?
  6. Exporting and Unexporting identifiers
    1. Depending on whether the 1th letter of the first name is uppercase or lowercase ...
    • I feel this chapter of the author said too much nonsense, in fact, a simple sentence can be said clearly!

Concurrent

  1. Logical processors?
    1. When performing blocking IO operation, detach; When IO is ready, attach again?
  2. A 1th example:
    1. Runtime. Gomaxprocs (1)//or runtime. NUMCPU ()
    2. VAR wg sync. Waitgroup//WG's usage can be directly read the document and the sample code to grasp it instantly?
    3. Wg. ADD (2)
    4. Go func () {
      defer WG. Done ()
      } ()
    5. Wg. Wait ()
  3. Scheduler can be interrupted automatically at Goroutines execution time? (Swap out?) Preemptive scheduling? This internal operation occurs in the FMT. When the printf call?
  4. Competitive conditions
    1. Read-write shared variables must be atomic;
    2. Detection Tool: Go build-race
    3. Method 1:atomic. AddInt64 (&counter, 1) #奇怪, how does the atomic package make a change to a int64 variable is atomic? Take advantage of platform-specific assembly instructions?
    4. Method 2:mutex Sync. Mutex = mutex. Lock () {...} mutex. Unlock ()
  5. More flexible, Channels
    1. Initialization
      1. Unbuffered: = make (chan int) #如果有一个没准备好, first action (send/Accept) wait
      2. Buffered: = Make (Chan string, 10)
        1. Close action: can still be accepted but cannot be sent again (task send originator)
    2. Send data: Buffered <-"Gopher"
    3. Accept data: Value: = <-buffered
  6. Rand. Seed (time. Now (). Unixnano ())

concurrency mode

  1. Runner: Monitoring run time and timeout termination
    1. Type Runner struct {
      1. Interrupt Chan os. Signal
      2. Complete Chan Error
      3. Timeout <-chan time. Time
      4. tasks []func (int)
    2. var errtimeout = errors. New ("Received timeout")//Pre-created Error object
    3. Func (R *runner) Add (Tasks ... func (int)) {r.tasks = append (R.tasks, Tasks ...)}//Note the arguments here;
    4. Func (R *runner) Start () error {//Run All Tasks and monitor time-out errors
      1. Signal. Notify (R.interrupt, OS. Interrupt)
      2. Go func () {r.complete <-r.run ()} ()
      3. Select {
        1. Case ERR: = <-r.complete:return err
        2. Case <-r.timeout:return Errtimeout
    5. Func (R *runner) run () error {...}//executes each task sequentially, slightly
    6. Func (R *runner) Gotinterrupt () bool {
      1. Select {
        1. Case <-r.interrupt: Signal. Stop (R.interrupt) return true//note here to check that there is no acceptance to the operating system interrupt
        2. The Default:return false//default branch makes the preceding <-r.interrupt operation not block (? Is it possible to lose interrupts?)
          • Note that the initialization: Interrupt:make (Chan os. Signal, 1), Timeout:time. After (duration),//To model OS interrupts and timeouts as special Chan
  2. Pooling
    1. Type Pool struct {
      1. M sync. Mutex//This is used to protect what? Chan is not self-synchronizing (protecting the assignment of closed variables??? By
      2. Resources Chan io. Closer
      3. Factory func () (IO. Closer, error)//This name is disgusting, it should be changed to Allocnewresource
      4. closed bool
    2. Func (P *pool) acquire () (IO. Closer, error) {
      1. Select {
        1. Case R, OK: = <-p.resources: ...
        2. Default:return P.factory ()
    3. Func (P *pool) Release (R io. Closer) {
      1. P.m.lock ()
      2. Defer P.m.unlock ()
      3. ...
      4. Select {Case p.resources <-r: ...//default:pool full, releasing resources directly
    4. Start Goroutine in the loop to prevent sharing the same index/counter variable:
      1. Go func (a int) {...} (i)
  3. Work
    1. Naming a bit of a problem, work () seems to be executework ()?

Standard library

  1. Http://sourcegraph.com/code.google.com/p/go/.GoPackage/io/.def/Writer, unable to access
  2. Logging
    1. Log. Setprefix ("TRACE:")
    2. Log. SetFlags (log. Ldate | Log. Lmicroseconds | Log. Llongfile)
    3. Log. PRINTLN/FATALLN/PANICLN ("message")
    4. const {
      1. Ldate = 1 << Iota
    5. Custom logger:
      1. var (Trace *log. Logger ...)
      2. Trace = log. New (Ioutil. Discard, "TRACE:", log. Ldate|log. Ltime|log. Lshortfile) # var Discard io. Writer = devnull (0)
    6. Stdin = NewFile (UIntPtr (syscall. Stdin), "/dev/stdin")//?
    7. Io. Multiwriter (file, OS. STDERR)//?
  3. Encoding/decoding
    1. Gresult struct {
      1. Gsearchresultclass string ' JSON: Members Within "Gsearchresultclass" '//struct require special JSON mapping declarations (tags metadata);
      2. ...
    2. gresponse struct {
      responsedata struct {
      Results []gresult ' JSON: "Results" '
      } ' JSON: ' ResponseData
      '
    3. Decoding:
      1. var gr gresponse
      2. Err = json. Newdecoder (resp. Body). Decode (&GR)
    4. Unmarshal:
      1. ERR: = json. Unmarshal ([]byte (JSON), &c)//?
      • More flexible analysis:?
        var c map[string]interface{}
        Err: = json. Unmarshal ([]byte (JSON), &c)//In this case the sense code in interface{} will be abused?
    5. Coding
      1. c: = Make (map[string]interface{})
      2. ...
      3. Data, err: = json. marshalindent (c, "", "")
  4. Input and output
    1. There seems to be nothing particularly worth saying (another set of API naming styles)

Testing and performance Benchmarks

  1. Listing01_test.go
    1. Func testdownload (t *testing. T) {
      t.Log ("Given the need to test downloading content.") #t. Errorf represents a test failure?
      ...
      resp, err: = http. Get (URL)
      defer resp. Body.close ()
  2. Func Sendjson (rw http. Responsewriter, R *http. Request) {
    1. U = ...
    2. rw. Header (). Set ("Content-type", "Application/json")
    3. rw. Writeheader (200)
    4. Json. Newencoder (rw). Encode (&u)
  3. ?
    1. R, _: = http. Newrequest ("GET", "/sendjson", nil)
    2. RW: = Httptest. Newrecorder ()
    3. http. Defaultservemux.servehttp (rw, R)
  4. Performance Benchmark
    1. func benchmarksprintf (b *testing. B) {
      b.resettimer ()
    2. go test-v-run= "None"-bench= "benchmarksprintf"/ /Number of runs?
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.