Golang 学习资料
资料
1.How to Write Go Code
https://golang.org/doc/code.html
2.A Tour of Go
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 学习资料的更多相关文章
- golang学习资料[Basic]
http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/index.html 基础语法 <Go By Exa ...
- golang学习资料
http://yougg.github.io/static/gonote/GolangStudy.html
- golang学习资料必备
核心资料库 https://github.com/yangwenmai/learning-golang
- Golang学习:sublime text3配置golang环境
最近导师让学习golang, 然后我就找了些有关golang的学习视频和网站. 昨天在电脑上下载了go tools, 之后在sublime上配置了golang的运行环境.By the way, 我的电 ...
- 【Go语言】学习资料
这段时间一直在看Go语言,6月3日Apple发布了swift发现里面竟然也有许多Go语言的影子,截至现在每天都在感觉到Go语言的强大.确实值得一学 今天在这里给园友们推荐一些Go语言的学习资料 网站 ...
- go语言,golang学习笔记2 web框架选择
go语言,golang学习笔记2 web框架选择 用什么go web框架比较好呢?能不能推荐个中文资料多的web框架呢? beego框架用的人最多,中文资料最多 首页 - beego: 简约 & ...
- go练习2-go的学习资料
好吧 我承认,有自己添加的内容也有从别人的blog 中 ctrl + c 的 官方:http://golang.org ,经常被封 中文手册的翻译:http://code.google.com/p/g ...
- Golang 学习笔记 目录总结
- 基础: 下载安装 声明变量的方法 数据的三种基础类型:bool,数字,string 数据类型:数组和切片 数据类型:Maps 条件判断以及循环 函数 包管理 package 指针 结构体 - 初步 ...
- Hello Kotlin! Kotlin学习资料
今天谷歌搞了条大新闻.宣布Kotlin成为android开发的一级(One Class)语言,这说明谷歌是被甲骨文恶心坏了,打算一步步脱离掉java或者说是甲骨文公司的束缚了.原先网上大家还琢磨着会不 ...
随机推荐
- C#生成唯一订单号
今天系统出了一个问题,发现生成的订单号存在重复的情况了,这是要命的bug,不马上解决,就会有投诉了 经过改进后的代码我先简单的放一下,后面在慢慢的写清楚整个流程 string key = " ...
- ajax post 提交数据和文件
方式一:常用的方式是通过form.serialize()获取表单数据,但是,这样有个弊端,文件不能上传 $.ajax({ url:'/communication/u/', type:'POST', d ...
- 基于pygame实现飞机大战【面向过程】
一.简介 pygame 顶级pygame包 pygame.init - 初始化所有导入的pygame模块 pygame.quit - uninitialize所有pygame模块 pygame.err ...
- java最小公倍数与最大公约数
import java.util.Scanner; /** * Created by Admin on 2017/3/26. */ public class test02 { public stati ...
- mssql sqlserver update delete表别名用法简介
转自:http://www.maomao365.com/?p=6973 摘要: 在sql脚本编写中,如果需要在update delete 中使用表别名的方法,必须按照一定的规则编写,否则将会出现相应 ...
- LINQ的求和 平均 最大 最小 分组 计数 等等
1.简单形式: var q = from p in db.Products group p by p.CategoryID into g select g; 语句描述:使用Group By按Categ ...
- Winform调用webapi
/// <summary> /// 调用api返回json /// </summary> /// <param name="url">api地址 ...
- 服务器体系(SMP, NUMA, MPP)与共享存储器架构(UMA和NUMA)
1. 3种系统架构与2种存储器共享方式 1.1 架构概述 从系统架构来看,目前的商用服务器大体可以分为三类 对称多处理器结构(SMP:Symmetric Multi-Processor) 非一致存储访 ...
- Windows Server 2016-管理站点复制(二)
为了保持所有域控制器上的目录数据一致和最新,Active Directory 会定期复制目录更改.复制根据标准网络协议进行,并使用更改跟踪信息防止发生不必要的复制,以及使用链接值复制以提高效率. 本章 ...
- 安装Window 10系统------计算机经验
为什么这次安装window10系统呢?不是和window7系统的安装方法一样么?如果你是这样的想的话,是不完全对的,因为window10系统的安装有些繁杂,需要耐心.下面我就准备了官方原版的windo ...