Golang Bible----Reading notes

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


Go language origins

Golang Development History

Go Language Project

    • "The complexity of the software is the multiplication-level related-----Rob Pike"
    • Simple design needs to discard unnecessary ideas at the beginning of the work, and to strictly differentiate between good and bad changes during the life cycle of the software. With enough effort, a good change can remain adaptive without destroying the original complete concept, as Fred Brooks "conceptual Integrity", while a bad change does not achieve this effect, they simply undermine the consistency of the original design through superficial and simple compromises. Only through simple design can a system maintain stability, security and continuous evolution.

The organization of the book


    • The first chapter contains the basic structure of this tutorial, through more than 10 programs on how to achieve similar to read-write files, text formatting, image creation, network client and server communication and other daily work.
    • The second chapter describes the basic elements of the Go Language program structure, variables, new type definitions, packages and files, as well as the scope of concepts.
    • The third chapter discusses numbers, Boolean values, strings, and constants, and shows how to display and manipulate Unicode characters.
    • The fourth chapter describes the composite types, from simple arrays, dictionaries, slices to dynamic lists.
    • The fifth chapter covers functions and discusses error handling, panic and recover, as well as defer statements.



    • The eighth chapter discusses concurrent programming based on sequential communication process (CSP) concept, using goroutines and channels to handle concurrent programming.
    • The Nineth chapter discusses the traditional concurrent programming based on shared variables.
    • The tenth chapter describes the package mechanism and the organizational structure of the package. This chapter also shows how to effectively use the tools that go comes with, using a single command to complete compilation, testing, benchmarking, code formatting, documentation, and many other tasks.
    • The 11th chapter discusses unit testing, the tools of the go language, and the standard library, which incorporate lightweight testing capabilities, avoiding a powerful but complex testing framework. The test library provides some basic artifacts that can be used to build complex test artifacts if necessary.
    • The 12th chapter discusses reflection, the ability of a program to examine itself during operation. Reflection is a powerful programming tool, but use it sparingly; This chapter uses the reflection mechanism to implement some important go language library functions, demonstrating the powerful use of reflection. The 13th chapter explains the details of the underlying programming and, if necessary, uses the unsafe package to bypass the Go language-safe type system.


Hello, World

尝试用100中方法打印出Hello, World
Ha ha!

package mainfunc main() {    print("Hello, 世界") //Go语言原生支持Unicode,它可以处理全世界任何语言的文本。}

Command-line arguments

The OS package provides a number of functions and variables that interact with the operating system in a cross-platform manner. The command line parameters of the program can be obtained from the args variable of the OS package, and the OS package is used externally. Args accesses the variable.

To find duplicate rows

    • bufioPackage, which makes processing input and output easy and efficient. The scanner type is one of the most useful features of the package, which reads the input and splits it into rows or words, usually the simplest way to handle input in the form of a row.
    • Formatting verb
      %d          十进制整数%x, %o, %b  十六进制,八进制,二进制整数。%f, %g, %e  浮点数: 3.141593 3.141592653589793 3.141593e+00%t          布尔:true或false%c          字符(rune) (Unicode码点)%s          字符串%q          带双引号的字符串"abc"或带单引号的字符'c'%v          变量的自然形式(natural format)%T          变量的类型%%          字面上的百分号标志(无操作数)
      ioutil.ReadFile(filename)function returns a byte slice (byte slice)

GIF animations

    • The generated graphic name is Lisa-shaped (Lissajous figures)


http. Get (URL)
Ioutil. ReadAll (resp. Body)

Get multiple URLs concurrently

Goroutine and Channel

Web Services

package mainimport (    "fmt"    "log"    "net/http")func main() {    http.HandleFunc("/", handler) // each request calls handler    log.Fatal(http.ListenAndServe("localhost:8000", nil))}// handler echoes the Path component of the requested URL.func handler(w http.ResponseWriter, r *http.Request) {    fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)}
    • If your request pattern is the/end, all URLs prefixed with that URL will be matched by this rule.


    • Control flow
        switch coinflip() {  case "heads":      heads++  case "tails":      tails++  default:      fmt.Println("landed on edge!")
      The go language does not need to explicitly write a break after each case
      If you want to perform the same logic for several adjacent case, you need to explicitly write a Fallthrough statement to override this default behavior.
    • Named type
    • Pointer
      A pointer is a data type that stores the memory address of a variable directly. The pointer is a visible memory address, the,& operator can return a variable's memory address, and the * operator can get the variable content pointed to by the pointer, but there is no pointer operation in the go language, that is, the pointer cannot be added or reduced as in C.
    • Methods and Interfaces
      Methods in the go language can be associated to any one of the named types.
    • Package
    • Comments

Program Structure


    • 25 Key Words
      break default func interface selectcase defer go map structchan else goto package switchconst fallthrough if range typecontinue for import return var
    • More than 30 pre-defined names
      内建常量: true false iota nil内建类型: int int8 int16 int32 int64uint uint8 uint16 uint32 uint64 uintptrfloat32 float64 complex128 complex64bool byte rune string error内建函数: make len cap new append copy close deletecomplex real imagpanic recover
    • Go language programmers recommend using Hump-style naming



    • Short variable Declaration
      i := 100
    • Pointer
      x := 1p := &x // p, of type *int, points to xfmt.Println(*p) // "1"*p = 2 // equivalent to x = 2fmt.Println(x) // "2"
    • New function
      p := new(int) // p, *int 类型, 指向匿名的 int 变量
    • The life cycle of a variable
      The go language's automatic garbage collector is a great help in writing the right code, but it doesn't mean you don't have to think about memory at all. You do not need to explicitly allocate and free memory, but to write efficient programs you still need to understand the life cycle of the variables. For example, if you save a pointer to a short life cycle object to an object with a long life cycle, especially when you save to a global variable, garbage collection of short life cycle objects (which can affect program performance) is blocked.

Assign value

    • Tuple assignment
      x, y = y, xa[i], a[j] = a[j], a[i]
    • can be assignable
      The assignable rules have different requirements for different types, and we will specifically explain each new type of special place. for the types we have discussed, its rules are simple: types must match exactly, nil can be assigned to any pointer or reference type variable. Constants (§3.6) have more flexible assignment rules, because this avoids unnecessary explicit type conversions.


Packages and files

    • Importing packages
      "fmt". "fmt" //省略包名_ "fmt" //只导入
    • Initialization of the package
      func init() { /* ... */ }


    • Do not confuse the scope and the life cycle. The scope of the declaration statement corresponds to a text area of the source code, which is a compile-time property. The life cycle of a variable is a valid time period when a variable exists in the program's runtime, which can be referenced by other parts of the program in this time zone; it is a runtime concept.
    • The control stream, which is the type of label followed by a break, continue, or Goto statement, is the scope of the function level.

Underlying data type

Integral type


    • Operator
      *(乘)      /(除)      %(余)      <<(左移)       >>(右移)     &(位运算 AND)       &^(位清空 (AND NOT))+(加)      -(减)      | (位运算 OR)     ^(位运算 XOR)==(等于)     != (不等于)    < (小于)     <=(小于或等于)       > (大于)     >=(大于或等于)&&(AND)||(OR)
      The binary operator has five priority levels. At the same priority, use the left precedence binding rule, but use parentheses to clarify precedence and use parentheses to elevate precedence

Floating point number


It's beautiful.
Copyright Alan A. Donovan & Brian W. kernighan.//LICENSE:HTTPS://CREATIVECOMMONS.ORG/LICENSES/BY-NC-SA/4 .0///See page 58.//!+//surface computes an SVG rendering of a-page surface function.package mainimport ("FMT" "Mat H ") const (width, height = max, +//canvas size in pixels cells = +//Numbe R of grid cells Xyrange = 30.0//axis ranges (-xyrange. +xyrange) Xyscale = WIDTH/2/xyrange//pixels per x or y unit zscale = height * 0.4//Pixel s per z unit angle = Math. PI/6//angle of x, y axes (=30°)) var sin30, cos30 = Math. Sin (angle), math. cos (angle)//sin (30°), cos (30°) func main () {FMT. Printf ("<svg xmlns= ' http://www.w3.org/2000/svg '" + "style= ' Stroke:grey; Fill:white; stroke-width:0.7 ' "+" width= '%d ' height= '%d ' > ", width, height) for i: = 0; I < cells; i++ {for J: = 0; J < cells; J + + {AX, Ay: = Corner (i+1, J) bx, By: = Corner (i, J) cx, cy: = Corner (i, j+1) dx, dy: = Corner ( I+1, j+1) fmt.     Printf ("<polygon points= '%g,%g%g,%g%g,%g%g,%g '/>\n ', ax, Ay, BX, by, CX, CY, DX, DY)}} Fmt.    Println ("</svg>")}func Corner (i, J int) (float64, float64) {//Find point (x, y) at corner of Cell (I,J).    x: = Xyrange * (float64 (i)/cells-0.5) y: = Xyrange * (float64 (j)/cells-0.5)//Compute surface height Z.    Z: = f (x, Y)//Project (z/y) isometrically onto 2-d SVG canvas (sx,sy). SX: = WIDTH/2 + (x-y) *cos30*xyscale sy: = HEIGHT/2 + (x+y) *sin30*xyscale-z*zscale return SX, Sy}func f (x, y Float6 4) float64 {r: = Math. Hypot (x, y)//Distance from (0,0) return math. Sin (r)/r}//!-


The go language provides two precision complex types: complex64 and complex128, respectively, corresponding to float32 and float64 two floating point precision. The built-in complex function is used to construct complex numbers, and built-in real and IMAG functions return the real and imaginary parts of the complex numbers, respectively:

Boolean type


\a      响铃\b      退格\f      换页\n      换行\r      回车\t      制表符\v      垂直制表符\'      单引号 (只用在 '\'' 形式的rune符号面值中)\"      双引号 (只用在 "..." 形式的字符串面值中)\\      反斜杠
    • Thanks to the excellent design of the UTF8 code, many string operations do not require decoding operations. We can directly test whether a string is a prefix of another string without decoding:
      func HasPrefix(s, prefix string) bool {    return len(s) >= len(prefix) && s[:len(prefix)] == prefix}
      Or a suffix test:
      func HasSuffix(s, suffix string) bool {     return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix}
      Or it contains a substring test:
      func Contains(s, substr string) bool {  for i := 0; i < len(s); i++ {      if HasPrefix(s[i:], substr) {          return true      }  }  return false}
package mainimport "fmt"func main() {    s := "Hello, 世界"    fmt.Printf("%s\t%d\n", s, len(s))    for i := 0; i < len(s); i++ {        fmt.Printf("%d\t%v\t%q\n", i, s[i], s[i])    }    fmt.Println("...")    for i, r := range s {        fmt.Printf("%d\t%d\t%q\n", i, r, r)    }}


Hello, 世界    130    72    'H'1    101    'e'2    108    'l'3    108    'l'4    111    'o'5    44    ','6    32    ' '7    228    'ä'8    184    '¸'9    150    '\u0096'10    231    'ç'11    149    '\u0095'12    140    '\u008c'...0    72    'H'1    101    'e'2    108    'l'3    108    'l'4    111    'o'5    44    ','6    32    ' '7    19990    '世'10    30028    '界'
    • String and byte slices
      Four packages in the standard library are especially important for string handling: bytes, strings, StrConv, and Unicode packages.
      • The strings package provides many functions such as querying, replacing, comparing, truncating, splitting, and merging strings.
      • The bytes package also provides a number of functions similar to the function, but for the []byte type] that has the same structure as the string. Because strings are read-only, building a string incrementally causes a lot of allocation and replication. In this case, use bytes. The buffer type will be more efficient and we'll show you later.
      • The StrConv package provides the conversion of Boolean, Integer, floating-point, and corresponding strings, as well as double-quote-escaping-related conversions.
      • The Unicode package provides similar features such as IsDigit, Isletter, Isupper, and Islower, which are used to categorize characters. Each function has a single parameter of type Rune, and then returns a Boolean value. Conversion functions such as ToUpper and ToLower are used to convert the case of Rune characters. All of these functions are categorized as letters, numbers, and so on, as defined by the Unicode standard. Strings packages also have similar functions, which are toupper and ToLower, which convert each character of the original string accordingly, and then return the new string.
    • Conversion of strings and numbers


    • Iota Constant Generator
      const ( _   = 1 << (10 * iota) KiB // 1024 MiB // 1048576 GiB // 1073741824 TiB // 1099511627776             (exceeds 1 << 32) PiB // 1125899906842624 EiB // 1152921504606846976 ZiB // 1180591620717411303424    (exceeds 1 << 64) YiB // 1208925819614629174706176)

Composite data types



    • Slice Memory Tips


In the go language, a map is a reference to a hash table, and the map type can be written as Map[k]v, where K and V correspond to key and value respectively.
The built-in make function creates a map:

ages := make(map[string]int) // mapping from strings to ints

We can also create a map with the syntax of map literals, as well as specify some initial key/value:

ages := map[string]int{ "alice": 31, "charlie": 34,}

Use the built-in delete function to delete an element:

delete(ages, "alice") // remove element ages["alice"]

Structural body

    • Comparison of structural bodies
      If all members of a struct can be compared, then the structure can be compared.

    • struct embedding and anonymous members

      • It is important to note that the%v parameter in the printf function contains the # adverb, which indicates that the value is printed in the same syntax as the go language. For struct types, the name of each member is included.
        fmt.Printf("%#v\n", w)


json.Marshaland thejson.MarshalIndent

    • JSON processing struct not exporting Members
      The name of the member in the Golang structure begins with a lowercase letter, so the other packets are inaccessible, that is, JSON cannot access the members that begin with the lowercase letters in our struct. Two methods of solution
      1. Members of a struct start with uppercase, and then add tag
  Package Mainimport ("Encoding/json", "FMT" "Log") type Movie struct {Title string year int '        JSON: "released" ' Color BOOL ' JSON: "Color,omitempty" ' Actors []string}func main () {var movies = []movie{        {Title: "Casablanca", year:1942, Color:false, Actors: []string{"Humphrey Bogart", "Ingrid Bergman"}}, {title: "Cool Hand Luke", year:1967, Color:true, Actors: []string{"Paul Newman"}}, {title: "Bullitt",    year:1968, Color:true, Actors: []string{"Steve McQueen", "Jacqueline Bisset"}},//...} Data, err: = json. Marshal (Movies)//JSON. Marshalindent (struct, "", "") if err! = Nil {log. Fatalf ("JSON Marshaling failed:%s", err)} FMT. Printf ("%s\n", Data)}  
[{"Title":"Casablanca","released":1942,"Actors":["Humphrey Bogart","Ingrid Bergman"]},{"Title":"Cool Hand Luke","released":1967,"color":true,"Actors":["Paul Newman"]},{"Title":"Bullitt","released":1968,"color":true,"Actors":["Steve McQueen","Jacqueline Bisset"]}]
    1. Implement JSON. Marshaler interface
      Package Main

Import (

Func Main () {
var s S
S.A. = 5
S.b[0] = 3.123
S.B[1] = 111.11
S.B[2] = 1234.123
S.C = "Hello"
S.d[0] = 0x55

j, _ := json.Marshal(s)fmt.Println(string(j))


Type S struct {
a int
b [4]float32
C string
d [12]byte

Func (this S) Marshaljson () ([]byte, error) {
Return JSON. Marshalindent (map[string]interface{}{//JSON. Marshalindent (struct, "", "")
"A": THIS.A,
"B": this.b,
"C": THIS.C,
"D": THIS.D,
}, "", " ")


Text and HTML templates


function declaration


Multiple return values


function value

anonymous functions

Variable parameters

Deferred function

Panic exception

    • In general, when an panic exception occurs, the program interrupts the operation and immediately executes the deferred function (defer mechanism) in the goroutine (which can be understood as threads, described in detail in chapter 8th)

Recover catching exceptions


Method declaration

A method based on a pointer object

To extend a type by embedding a struct

Method values and Method expressions

Bit array



When designing a new package, the new Go programmer always starts by creating a collection of interfaces and later defines the specific types that satisfy them. The result of this approach is that there are many interfaces, each of which has only one implementation. Don't do it again. This interface is an unnecessary abstraction; they also have a run-time loss. You can use the export mechanism (§6.6) to restrict whether a field of a type or a struct is visible outside the package. An interface is required only if there are two or more than two specific types that must be processed in the same way.
When an interface is implemented only by a single concrete type, there is an exception, due to its dependency, that the specific type cannot exist in the same package as the interface. In this case, an interface is a good way to decouple the two packages.
Because the interface is used only when two or more types implement an interface in the go language, they are bound to be abstracted from any particular implementation detail. The result is fewer and simpler methods (often and IO. Writer or FMT. A smaller interface with only one stringer. Small interfaces are easier to meet when new types appear. A good standard for interface design is ask only for what do you need (just think about the things you need)

Goroutines and Channels

Concurrency based on shared variables

Packages and tools



Go test


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.