资料

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

Golang 学习资料的更多相关文章

  1. golang学习资料[Basic]

    http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/index.html 基础语法 <Go By Exa ...

  2. golang学习资料

    http://yougg.github.io/static/gonote/GolangStudy.html 

  3. golang学习资料必备

    核心资料库 https://github.com/yangwenmai/learning-golang

  4. Golang学习:sublime text3配置golang环境

    最近导师让学习golang, 然后我就找了些有关golang的学习视频和网站. 昨天在电脑上下载了go tools, 之后在sublime上配置了golang的运行环境.By the way, 我的电 ...

  5. 【Go语言】学习资料

    这段时间一直在看Go语言,6月3日Apple发布了swift发现里面竟然也有许多Go语言的影子,截至现在每天都在感觉到Go语言的强大.确实值得一学 今天在这里给园友们推荐一些Go语言的学习资料 网站 ...

  6. go语言,golang学习笔记2 web框架选择

    go语言,golang学习笔记2 web框架选择 用什么go web框架比较好呢?能不能推荐个中文资料多的web框架呢? beego框架用的人最多,中文资料最多 首页 - beego: 简约 & ...

  7. go练习2-go的学习资料

    好吧 我承认,有自己添加的内容也有从别人的blog 中 ctrl + c 的 官方:http://golang.org ,经常被封 中文手册的翻译:http://code.google.com/p/g ...

  8. Golang 学习笔记 目录总结

    - 基础: 下载安装 声明变量的方法 数据的三种基础类型:bool,数字,string 数据类型:数组和切片 数据类型:Maps 条件判断以及循环 函数 包管理 package 指针 结构体 - 初步 ...

  9. Hello Kotlin! Kotlin学习资料

    今天谷歌搞了条大新闻.宣布Kotlin成为android开发的一级(One Class)语言,这说明谷歌是被甲骨文恶心坏了,打算一步步脱离掉java或者说是甲骨文公司的束缚了.原先网上大家还琢磨着会不 ...

随机推荐

  1. JS怎样实现图片的懒加载以及jquery.lazyload.js的使用

    在项目中有时候会用到图片的延迟加载,那么延迟加载的好处是啥呢? 我觉得主要包括两点吧,第一是在包含很多大图片长页面中延迟加载图片可以加快页面加载速度:第二是帮助降低服务器负担. 下面介绍一下常用的延迟 ...

  2. VS2017 docker部署工具的使用

    **简要描述:** - VS2017的docker支持工具,支持对.Net Framework,.Net Core控制台或者Web应用,在docker中生成,调试,运行.对于.Net Framewor ...

  3. Nginx 集群 反向代理多个服务器

    准备多个服务器,使用 nginx 先做好代理(我这里只有一台服务器,就拷贝两个 tomcat 了,端口分别设置为 8081 和 8082) 1,复制 tomcat cp -r apache-tomca ...

  4. Android滑动冲突解决

    (1).场景一:外部滑动方向跟内部滑动方向不一致,比如外部左右滑动,内部上下滑动   ViewPager+Fragment配合使用,会有滑动冲突,但是ViewPager内部处理了这种滑动冲突   如果 ...

  5. 关于最新笔记本机型预装win8如何更换为win7的解决办法

    关于最新笔记本机型预装win8如何更换为win7的解决办法 目前新出的很多机型出厂自带的都是win8系统,可能有些人用不习惯,想更换为win7系统,但是由于这些机型主板都采用UEFI这种接口(硬盘分区 ...

  6. codeforces 632C The Smallest String Concatenation

    The Smallest String Concatenation 题目链接:http://codeforces.com/problemset/problem/632/C ——每天在线,欢迎留言谈论. ...

  7. python 冒泡、二分查找

    冒泡: import random def _sort(_lst): count = 1 while count < len(_lst): for i in range(0, len(_lst) ...

  8. Unity3D 4.x编辑器操作技巧

    unity wiki(en chs)   unity官网 unity manual(chs  官方最新) 各个版本unity编辑器下载地址: https://unity3d.com/cn/get-un ...

  9. 智能ERP主副机设置

    智能ERP主副机设置 1. 将主机的电脑设置成固定IP,IP地址请自行设置,设置好后需要记住,配置副机的时候会用到 2. 在主机上安装智能ERP,安装完后,会弹出数据库配置,主机直接点校验 3. 校验 ...

  10. MyBatis笔记----多表关联查询两种方式实现

    数据库 方式一:XML 按照下面类型建立article表 Article.java package com.ij34.model; public class Article { private int ...