Golang 学习资料

资料

1.How to Write Go Code

https://golang.org/doc/code.html

2.A Tour of Go

https://tour.golang.org/list

3.Effective Go

https://golang.org/doc/effective_go.html

4.Visit the documentation page for a set of in-depth articles about the Go language and its libraries and tools.

https://golang.org/doc/#articles

Packages,variables,and functions

Packages

  • Every Go program is made up of packages
  • Programs start running in package main
  • In Go,a name is exported if it begins with a capital.

Functions

  • type comes after the variable name.
  • When two or more consecutive named function parameters share a type,you can omit the type from all but the last.
  • A function can return any number of results

Variables

  • The var statement declares a list of variables
  • Inside a function,the := short assigment statement can be used in place of a var declaration with implicit type.
  • Variables declared without an explicit initial value are given their zero value.
  • The expression T(v) converts the value v to the type T.Go assignment between items of different type requires an explicit conversion.
  • Constants are declared like variables,but with the const keyword(Constants cannot be declared using the := syntax)

Flow control statements: for,if,else,switch and defer

for

  • unlike other languages like C,java there are no parentheses surrounding the three components of the for statement and the braces {} are always required.
  • The init statement will often be a short variable declaration,and the varaibles there are visible only in the scope of the for statement
  • The init and post statements are optional.
  • You can drop the semicolons:C's while is spelled for in Go.
  • If you omit the loop condition it loops forever,so an infinite loop is compactly expressed.

If

  • Go's if statements are like its for loops;the expression need not be surrounded by parentheses() but the braces {} are required.
  • Like for,the if statement can start with a short statement to execute before the condition
  • Variables declared inside an if short statement are also available inside any of the else blocks.

sort:

package main

import (
    "fmt"
)

func main(){
    arr := []int{1,5,3,2,6,3,4,8,7,0}
    
    for i:=0;i<len(arr);i++{
        fmt.Printf("%d ",arr[i]);
    }
    fmt.Printf("\nSorting\n");
    
    for i:=0;i<len(arr);i++{
        for j:= i+1;j<len(arr);j++{
            if arr[i]>arr[j]{
                arr[i],arr[j] = arr[j],arr[i]
            }
        }
    }
    
    for i:=0;i<len(arr);i++{
        fmt.Printf("%d ",arr[i]);
    }
    fmt.Printf("\n");
}

Switch

  • In effect,the break statement that is needed at the end of each case in those languages(C,C++) is provided automatically in Go.
  • Go's switch cases need not be constants,and the values involved need not be integers
  • Switch cases evaluate cases from top to bottom,stopping when a case succeeds.
  • Switch without a condition is the sames as switch true.

Defer

  • A defer statement defers the execution of a function until the surrounding function returns.The deferred call's arguments are evaluated immediately.
  • Deferred function calls are pushed onto stack.When a function returns,its deferred calls are executed in last-in-first-out-order.

More types:structs,slices,and maps.

Pointers

  • The type *T is a pointer to a T value.Its zero value is nil.
  • Unlike C,Go has no pointer arithmetic

Structs

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

Pointers to struct

  • To access the field X of a struct when we have the struct pointer p we could write (*p).X.However,that notation is cumbersome,so the language permits us instead to write just p.X,without the explicit dereference.

Struct Literals

  • A struct literal denotes a newly allocated struct value by listing the values of its fields.You can list just a subset of fields by using the Name: syntax.

Arrays

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

Slices

  • An array has a fixed size.A slice ,on the other hand , is a dynamically-sized,flexible view into the elements of an array.
  • The type []T is a slice with elements of type T.
  • A slice if formed by specifying two indices,a low and high bound,separated by a colon:a[low:high],This selects a half-open range which includes the first element,but excludes the last one.

Slices are like reference to arrays

  • A slice does not store any data,it just describes a section of an underlying array.
  • Changing the elements of a slice modifies the corresponding elements of its underlying array.
  • Other slices that share the same underlying array will see those changes.

Slice literals

  • A slice literal is like an array literal without the length

Slice defaults

  • When slicing,you may omit the high or low bounds to use their defaults instead.The default is zero for the low bound and the length of the slice for the high bound.

Slice length and capacity

  • A slice has both a length and a capacity.
  • The length of a slice is the number of elements it contains
  • The capacity of a slice is the number of elements in the underlying array,counting from the first element in the slice.
  • The length and capacity of a slice s can be obtained using the expression len(s) and cap(s)

Nil Slices

  • The zero value of a slice is nil.

Creating a slice with make

  • Slices can be created with the built-in make function;this is how you create dynamically-sized arrays.
  • The make function allocates a zeroed array and returns a slice that refers to that array:
a:=make([]int,5)//len(a)=5
  • To specify a capacity,pass a third argument to make:

Appending to a slice

  • it is common to append new elements to a slice,and so Go provides a built-in append function.
func append(s []T,vs ....T)[]T
  • The resulting value of append is a slice containing all the elements of the original slice plus the provided values.
  • 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 loop iterates over a slice or map.
  • When ranging over a slice,two values are returned for each iteration.The first is the index,and the second is a copy of the element at that index.
  • You can skip the index or value by assigning to _.
  • If you only want the index,drop the , value entirely.

Maps

  • A map maps keys to values.
  • The make function returns a map of the given type,initialized and ready for use.
  • Delete an element:
delete(m,key)
  • Test that a key is present with a two-value assignment:
elem,ok = m[key]

if key is not in the map,then elem is the zero value for the map's element type.

Function values

  • Functions are values too.They can be passed around just like other values.
  • Function values may be used as function arguments and return values

Function closures

  • Go functions may be closures.A closure is a function value that referenes variables from outside its body.The function may access and assign to the referenced variables;in this sense the function is "bound" to the variables

Methods and interfaces

Method

  • Go does not have classes.However,you can define methods on types.
  • A method is a function with a special receiver argument.
  • The receive appears in its own argument list between the func keyword and the method name.
  • Remember:a method is just a function with a receiver argument.
  • You cannot declare a method with a receiver whose type is defined in another package(which includes the built-in types such as int)
  • You can declare methods with pointer receivers.This means the receiver type has the literal syntax T for some type T.(Also,T cannot itself be a pointer such as int.)

Methods and pointer indirection

  • methods with pointer receivers take either a value or a pointer as the receiver when they are called.(The equivalent thing happends in the reverse direction)

Choosing a value or pointer receiver

  • There are two reasons to use a pointer receiver.
  • The first is so that the method can modify the value that its receiver points to.
  • The second is to avoid copying the value on each method call.This can be more efficient if the receiver is a large struct.
  • In general,all methods on a given type should have either value or pointer receivers,but not a mixture of both.

Interfaces

  • An interface type is defined as a set of method signatures.
  • A value of interface type can hold any value that implements those methods.

Interfaces are implemented implicitly

  • A type implements an interface by implementing its methods.There is no explicit declaration of intent,no "implements" keyword.

Interface values

  • Under the hood,interface values can be thought of as a tuple of a value and a concrete type:
  • An interface value holds a value of a specific underlying concrete type.
  • Calling a method on an interface value executes the method of the same name on its underlying type.

Interface values with nil underlying values

  • If the concrete value inside the interface itself is nil,the method will be called with a nil receiver.
  • Note that an interface value that holds a nil concrete value is itself non-nil

Nil interface value

  • A nil interface value holds neither value nor concrete type.

The empty interface

  • The interface type that specifies zero methods is known as the empty interface.
  • An empty interface may hold values of any type.
  • Empty interfaces are used by code that handles vallues of unknown type.

Type assertions

  • A type assertion provides access to an interface value's underlying concrete value.
t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

Type switches

  • A type switch is a construct that permits serveral type assertions in series.
switch v := i.(type){
    case T:
        //here v has type T
    default:
        //no match
}

A type switch is like a regular switch statement,but the cases in a type switch specify type(not value),and those values are compared against the type of the value held by the given interface value.

The declaration in a type switch has the same syntax as a type assertion i.(T),but the specific type T is replaced with the keyword type.

Stringers

one of the most ubiquitous interfaces is Stringer defined by the fmt package.

type Stringer interface{
    String() string
}

A Stringer is a type that can describe itself as string.The fmt package look for this interface to print values.

Errors

Go programs express error state with error values.

  • A nil error denotes success;a non-nil error denotes failure.

Reader

  • The io package specifies the io.Reader interface,which represents the read end of a stream of data.
  • The Go standard library contains many implementations of these interfaces,including files,network connections,compressors,ciphers,and others.
  • The io.Reader interface has a Read method:
func (T)Read(b []byte)(n int,err error)

Read populates the given byte slice with data and returns the number if bytes populated and an error value.It returns an io.EOF error when the stream ends

Image

Package image defines the Image interface

package image
type Image interface{
    ColorModel() color.Model
    Bounds() Rectangle
    At(x,y int) color.Color
}

Concurrency

Goroutines

A goroutine is a lightweight thread managed by by the Go runtime.

go f(x,y,z)

starts a new goroutine running

f(x,y,z)

Goroutines run the same address space,so access to shared memory must be synchronized.The sync package provides useful primitives,althought you wan't need them much in Go as there are other primtives.

Channels

  • Channels are a typed conduit through which you can send and receive values with the channel operator,<-
  • Like maps and slices,channels must be created before use:
ch:=make(chan int)
  • By default,sends and receives block until the other side is ready.This allows goroutines to synchronize without explicit locks or condition variables.

Buffered Channels

  • Channels can be buffered.Provide the buffer length as the second argument to make to initialize a buffered channel:
ch := make(chan int,100)
  • 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:
v,ok:=<-ch
  • The loop for i:= range c receives values from the channel repeatedly until it is closed.

Select

  • The select statement lets a goroutine wait on multiple communication operations.
  • A select blocks until one of its cases can run,then it executes that case.It chooses one at random if multiple are ready.

Default Selection

  • The default case in a select is run if no other case is ready.
  • Use a default case to try a send or receive without blocking
select {
case i := <-c:
    //use i
default:
    //receiving frim c would block
}

sync.Mutex

What if we just want to make sure only one goroutine can access a variable at a time to avoid conflicts

The concept is called mutual exclusion,and the conventional name for the data structure that provides it is mutex

Go's standard libaray provides mutual exclusion with sync.Mutext and its two methods:

Lock
Unlock

转载于:https://www.cnblogs.com/r1ng0/p/10196858.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值