目的:方便以后自己查阅一些基础东西。基本上是纯摘抄。
对Cpp熟悉的话,基本可以一天速通就去做lab了。不过面向对象,什么interface可能要适应一下。

Basic

Packages

Every Go program is made up of packages.
Programs sart running in package main.

By convention , the package name is the same as the last element of the import path . For example ,import "math/rand" ,we just need to use rand.xxx.

Exported names :
In Go, a name is exported if it begins with a capital letter. When importing a package, you can refer only to its exported names. Any "unexported" names are not accessible from outside the package.

Functions

A function can take zero or more arguments.

A function can return any number of results.

Named return values: Go's return values may be names. If so ,they are treated as variables defined at the top of the function. A retrun statement without arguments returns the named return values. Naked return statements should be used only in short functions

Basic types

Zero values

Variables declared without an explicit initial value are given their zero value.

The zero value is :
0 for numric types
false for the boolean type
""(the empty string) for strings

Type conversions

Unlike in C or cpp,Go assignment between items of different type requires an explicit conversion.

Constans

Constatns are delcared like variables, but with the const keywork. Constants can be character,string,boolean, or numericvalues. Constans cannot be declared using the := syntax.

Numeric Constants : Numeric constatns are high-precison values.

An untyped constant takes the type needed by tis context.

Control

Go has only one looping construct , the for loop.

Three components (The init and post statements are optional):

  1. the init statement : executed before the first iteration
  2. the condition expression : evluated before every iteration
  3. the post statement : executed at the end of every iteration

If

Simliar with for

If with a short statement

Like for, the if statement can start with a short statement to execute before the conditon.

Variables delcared by the statement are only in scpoe until the end of the if.

Else

Same with C or Cpp

Switch

Go's swithc is like the one in C,C++ Java... , except that Go only runs the selected case, not all the cases that follow. Another important difference is that Go's swich cases need not be constatns, and the values involved need not be integers.

Order : from top to bottom, stopping when a case succeds.

Switch without a condition is the same as switch true(default: ).

defer

A defer statement defers the excution of a function until the surrouding function returns. The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrouding function returns.(RAII : like mutex)

Stacking defers : last-in-first-out order

Data abstraction

Pointers

Go has pointer. A pointer holdds the memory address of a value.

Structs

A struct is a collection of fields. Struct fields are accessed using a dot.

Pointers to structs : instead of write (*p).X , we could write p.X without the explicit dereference.

Arrays

The type [n]T is an array of n values of type T.

An array's length is part of its type, so arrays cannot be resized.

Slices

An array has a fixed size. A slice , on the other hand , is a dynamically-sized,flexible view into the elments of an array.

The type []T is a lice with elements of type T.

A slice is formed by specifying two indices, a low and high bound , separated by a colon (include the first elementbut excludes the last one).

Slices are like references to arrays

Slice length and capacity

A slice has both a length and a capacity.

Length : the number of elemtns it contains

Capacity : the number of elements in the underlying array, couting from the first element in the slice.

The zero value of a slice is nil.

Slices can be created with the build-in make function; this is how you create dynamically-sized arrays.

Appending to a slice

Use built-in append function.

If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.

Range

The range form of the for loop iterates over a slice or a map. When ranging over a slice,two values are returned for each iteration. Ther first is the index, the second is a copy of the element at that index.

Maps

A map maps keys to values

The zero value of a map is nil. A nil map has no keys, nor can keys be added

Function values

Function values may be used as function arguments and return values.

Function closures(unique)

A closure is a function value that references variables from outside its body.

Methods and interfaces

这里是Go面向对象的体现?对于Cpp选手,这样的面向对象可能会有点难受。但看过《设计模式》那本书以后,发现我们只用换种思维就可以适应Go的面向对象,Go的面向对象是很贴合设计模式所描述的内容的。

A method is a cuntion with a special reciver argument. (也就是Cpp里的类函数)
The receiver appears in its own argument list between the func keyword and the method name.

Delare a method on non-struct types.

Important: You can only a declare a method with a receiver whose type is defined in the same package as the method.

Pointer receivers

Methods with pointer recivers can modify the value to which the reciver points. Since method often need to modify their receiver, pointer recivers are more common than value recivers.(仅限于Method,function 不支持这样的转换)

Two reason to use a pointer reciver:
(1) : Modify the value
(2): Avoid copying

Interfaces

An interface type is defined as a set of method signatures.

A type implements an interface by implementing its methods.

Implicit interfaces decouple the defintion of an interface from its implementation.

If the concrete value inside the interface itself is ni, the method will be called with a nil receiver.

Empty interface

Empty interfaces are used by code that handles values of unknow type.

Type assertions

A type assertion provides accesss to an interface value's underlying concrete value.

If i does not hold a T, the statement will trigger a panic.

Type switches

A type switch is a construct that permits several type assertions in series.

Errors

Go programs express error state with error values.
The error type is a built-in interface similar to fmt.Stringer :

Readers

The io package specifies the io.Reader interface, which represents the read end of a stream data.

Generics(泛型)

Learn how to use type parameters in Go Functions and structs

暂时不需要这个。

Concurrency

Goroutines(协程)

A goroutine is all lightweight thread managed by the Go runtime.
Gouroutines run in the same address space, so access to shared memory must be synchronized.They sync package provides useful primitives(mutex).

Channels(thread-safe queue)

Channels are a typed conduit through which you can send and recive values with the channel.

By default, sends and receives block until the other side is ready.This allows goroutines to synchronize without explicit locks or conditon variables.

Buffered Channels

Channels can be buffered. Provice the buffer length as the second argument to make to initialize a buffered channel:

Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.

Range and close

A sender can close a channel to indicate that no more values will be sent . Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression after(unblock channel):

The loop for i := range c receives values from channel repeatedly until it is close.

Only the sender should close a channel.

Channels aren't like files; you don't usually need to close them.Closing is only necessary when the receiver must be told there are no more values coming,such as to terminate a range loop.

Select

The select statement lets a goroutine wait on multiple communication operations.

A select blocks unitl one of its cases can run , then it executes that case.It choose one at random if multiple are ready.

Default Selection

The default case in a select is run if no other case is ready.(non-block)

Mutex

和c++ 一样,不过可以用defer实现类似于lock_guard一样的东西。