Go language Learning

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

Go Language Rookie Tutorial: http://www.runoob.com/go/go-tutorial.html

Practical Go Programming: http://docscn.studygolang.com/doc/effective_go.html

Online Go Run Environment: HTTPS://TOUR.GOLANG.ORG/WELCOME/1

Go installation: Refer here to install on Windows very easy:http://www.runoob.com/go/go-environment.html

Go Chinese standard library (ctrl+f): http://docscn.studygolang.com/pkg/#stdlib

Go English package Index and search engine: https://godoc.org/

/************************************************************************************************************** ********/

gofmtThe program indents and aligns the GO program to the standard style, preserves annotations, and re-formats as needed. If you want to know how to handle some new code layouts, try running gofmt ;

Semicolons do not appear in the source code. The lexical analyzer automatically inserts a semicolon. Can be summed up as: "If the mark before the new line is the end of the statement, insert a semicolon." The opening brace cannot be placed on the next line, and if you do this, a semicolon is inserted in front of the curly brace, which can cause unwanted effects.

Go no longer uses do or while loops, there is only one more general for ; be more flexible; you switch if switch can accept optional initialization statements as you like for ; In addition, there is a new control structure that includes a type selection and a multiplexed communication multiplexer: select 。 Its syntax is slightly different: there are no parentheses, and the body must always be surrounded by braces.

By adding a space between the variable and the operator, the program looks more beautiful.

Go Language data type

Boolean type
The value of a Boolean can only be a constant true or false. A simple example: var b bool = True.

Number Type
integer int and floating-point Float,go languages Support integer and floating-point numbers, and natively support complex numbers, where bits are operated in complement.

Go also has schema-based types, such as: int, uint, and uintptr. Uint8uint16uint32uint64int8int16int32int64

Floating-point type:float32, float64. Complex64 (32-bit real and imaginary ) complex128 (64-bit real and imaginary )

String type:
A string is a sequence of characters concatenated with fixed-length characters. The string of Go is connected by a single byte. The byte of the Go language uses UTF-8 encoding to identify Unicode text.

Go language variable

The Go language variable name consists of a letter, a number, an underscore, where the first letter cannot be a number.

The general form of declaring variables is to use the var keyword.

First, the variable type is specified, and if the value is not assigned after declaration, the null pointer is nilwith the default value.

var name typename = value

Second, the variable type is determined by the value itself

var name = valuevar e, f = 123, "hello"

Third, omit Var, note: The variable on the left should not be declared, otherwise it will cause a compilation error. This can only occur in the body of the function without a declarative format. the system automatically infers and initializes the declaration.

name := value//只能在函数体中出现// 例如var a int = 10var b = 10c : = 10

Fourth, multi-variable declaration (important)

//类型相同多个变量, 非全局变量var vname1, vname2, vname3 typevname1, vname2, vname3 = v1, v2, v3var vname1, vname2, vname3 = v1, v2, v3 //和python很像,不需要显示声明类型,自动推断vname1, vname2, vname3 := v1, v2, v3 //出现在:=左侧的变量不应该是已经被声明过的,否则会导致编译错误// 这种因式分解关键字的写法一般用于声明全局变量var (    vname1 v_type1    vname2 v_type2)

Value types and reference types

All basic types, such as int, float, bool, and string, are value types that use variables of these types to point directly to a value that exists in memory. When using the equal sign to assign the value = of a variable to another variable, such as: j = i , the value of I is actually copied in memory.

If you declare a local variable and do not use it in the same code block, you will get a compilation error (a declaredand not used) but the global variable is allowed to be declared but not used.

Multivariable (declared) can be assigned on the same line, such as:

a, b, c = 5, 7, "abc"//未声明,用:=a, b, c := 5, 7, "abc"

The blank identifier _ is also used to discard values, such as the value 5 in: _, B = 5, 7 is discarded. _ is actually a write-only variable, you can't get its value. This is done because you have to use all the declared variables in the Go language , but sometimes you don't need to use all the return values from a function.

Go Language Constants

const identifier [Type] = value

Constants can also be used as enumerations:

const (    Unknown = 0    Female = 1    Male = 2)

The Magical Iota

/*iota,特殊常量,可以认为是一个可以被编译器修改的常量。在每一个const关键字出现时,被重置为0,然后再下一个const出现之前,每出现一次iota,其所代表的数字会自动增加1。iota 可以被用作枚举值:*/const (    a = iota    b = iota    c = iota)//简写形式const (    a = iota    b    c)const (            a = iota   //0            b          //1            c          //2            d = "ha"   //独立值,iota += 1            e          //"ha"   iota += 1            f = 100    //iota +=1            g          //100  iota +=1            h = iota   //7,恢复计数            i          //8    )

A more magical use:

package mainimport "fmt"const (i=1<<iota  // i=1<<0     j=3<<iota  // j=3<<1    k          // k=3<<2 12    l          // j=3<<3 24)func main() {fmt.Println("i=",i)fmt.Println("j=",j)fmt.Println("k=",k)fmt.Println("l=",l)}//以上运行结果为:i= 1j= 6k= 12l= 24

Logical Operators && | | ! is to judge whether it is true

bitwise operators &, |, and ^

The bitwise operator operates on an integer in-memory bits. Other bits A & 0x7fffffff for a 32-bit negative number to take a non-sign bit

Go language switch statement

Variable var1 can be of any type, while Val1 and val2 can be any value of the same type. There is no need to add a break after the match, end after running.

//Go 编程语言中 switch 语句的语法如下:switch var1 {    case val1:        ...    case val2:        ...    default:        ...}package mainimport "fmt"func main() {   /* 定义局部变量 */   var grade string = "B"   var marks int = 90   switch marks {      case 90: grade = "A"      case 80: grade = "B"      case 50,60,70 : grade = "C"      default: grade = "D"     }   switch {      case grade == "A" :         fmt.Printf("优秀!\n" )           case grade == "B", grade == "C" :         fmt.Printf("良好\n" )            case grade == "D" :         fmt.Printf("及格\n" )            case grade == "F":         fmt.Printf("不及格\n" )      default:         fmt.Printf("差\n" );   }   fmt.Printf("你的等级是 %s\n", grade );      }

Go Language SELECT statement

Select is a control structure in go, similar to the switch statement used for communication. Each case must be a communication operation, either sent or received. Select executes a running case randomly. If there is no case to run, it will block until there is one to run. A default clause should always be operational.

The syntax for the SELECT statement is described below:

*每个case都必须是一个通信*所有channel表达式都会被求值*所有被发送的表达式都会被求值*如果任意某个通信可以进行,它就执行;其他被忽略。*如果有多个case都可以运行,Select会随机公平地选出一个执行。其他不会执行。 *否则:*如果有default子句,则执行该语句。*如果没有default字句,select将阻塞,直到某个通信可以运行;Go不会重新对channel或值进行求值。
package mainimport "fmt"func main() {   var c1, c2, c3 chan int   var i1, i2 int   select {      case i1 = <-c1:         fmt.Printf("received ", i1, " from c1\n")      case c2 <- i2:         fmt.Printf("sent ", i2, " to c2\n")      case i3, ok := (<-c3):  // same as: i3, ok := <-c3         if ok {            fmt.Printf("received ", i3, " from c3\n")         } else {            fmt.Printf("c3 is closed\n")         }      default:         fmt.Printf("no communication\n")   }    }

Go language for Loop

Use with break,continue; the For loop of the Go language has 3 forms, only one of which uses semicolons:

//和 C 语言的 for 一样:for init; condition; post { }//和 C 的 while 一样,取代while:for condition { }//和 C 的 for(;;) 一样:for { }

The range format for the for loop can iterate over slice, map, array, string, and so on. The format is as follows:

for key, value := range oldMap {    newMap[key] = value}

Go language Functions

The Go language function defines the following format:

func f(参数) (返回值) {   函数体}//返回多个值func swap(x, y string) (string, string) {   return y, x}/* 函数返回两个数的最大值 */func max(num1, num2 int) int {   var result int   if (num1 > num2) {      result = num1   } else {      result = num2   }   return result }

Functions are used as values:

package mainimport (   "fmt"   "math")func main(){   getSquareRoot := func(x float64) float64 {      return math.Sqrt(x)   }   fmt.Println(getSquareRoot(9))}

Go Language anonymous function

func(参数列表) (返回值列表) {       函数体... }
    //直接使用,无参数直接加括号    func() int {        var i int =5        fmt.Printf("func 1\n")        return i    }()   //直接使用,有参数,在括号里加参数    func(arge int)  {          fmt.Printf("func %d\n",arge)    }(2)  //也可以先赋给一个变量再调用   a := func() int {          fmt.Printf("func 3\n")          return 5     }   a()

Go language Array

    • The array is a value. Assigning an array to another array copies all its elements.
    • A slice holds a reference to the underlying array, and if you assign a slice to another slice, they reference the same array.
    • In particular, if an array is passed into a function, it will receive a copy of the array rather than a pointer.
    • The size of the array is part of its type. Types [10]int and [20]int are different.

The Go language Array declaration needs to specify the element type and the number of elements, with the syntax in the following format:

var name [SIZE] type//var a [10] int//数组初始化:var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}//如果忽略[]中的数字不设置数组大小,Go 语言会根据元素的个数来设置数组的大小:var balance = []float32{1000.0, 2.0, 3.4, 7.0, 50.0}

Go Language Multidimensional arrays

var variable_name [SIZE1][SIZE2]...[SIZEN] variable_type//var threedim [5][10][4]intvar a = [3][4]int{   {0, 1, 2, 3} ,   /*  第一行索引为 0 */ {4, 5, 6, 7} ,   /*  第二行索引为 1 */ {8, 9, 10, 11}   /*  第三行索引为 2 */}

Go language passes an array to a function

//指定大小void myFunction(param [10]int){...}//不指定大小void myFunction(param []int){...}//例子func getAverage(arr []int, size int) float32 {   var i,sum int   var avg float32     for i = 0; i < size;i++ {      sum += arr[i]   }   avg = float32(sum / size)   return avg;}

Go language pointers

//指针声明格式如下:var name *type//打印指针地址%x:fmt.Printf("变量的地址: %x\n", &a )//Go 空指针,它的值为 nilif(ptr == nil)

Go language pointer array

声明整型指针数组(数组每个元素都是指针):var ptr [3]*int;

Go language Pointer to pointer

var ptr **int;

Go language pointers as function parameters

func swap(x *int, y *int) {   var temp int   temp = *x    /* 保存 x 地址的值 */   *x = *y      /* 将 y 赋值给 x */   *y = temp    /* 将 temp 赋值给 y */

GO language Structure

defining struct and declaring variables

//结构体定义需要使用 type 和 struct 语句。//type 语句设定了结构体的名称。结构体的格式如下:type my_type struct {   name1 type1   name2 type2   ...}一旦定义了结构体类型,它就能用于变量的声明,语法格式如下:name := my_type {value1, value2...valuen}//例子:type Books struct {   title string   author string   subject string   book_id int}var Book1 BooksBook1.title = "Go 语言"Book1.author = "www.runoob.com"Book1.subject = "Go 语言教程"Book1.book_id = 6495407//结构体作为函数参数func printBook( book Books ) {}//结构体指针var ptr *Books

Go language slices (Slice)

The Go language slice is an abstraction of an array. The length of the Go array cannot be changed. Slice ("dynamic array"), length is not fixed

A slice holds a reference to the underlying array, and if you assign a slice to another slice, they reference the same array.

声明一个未指定大小的数组来定义切片:var name []type或使用make()函数来创建切片:var slice1 []type = make([]type, len)或者make([]T, length, capacity)//capacity是可选参数也可以简写为:slice1 := make([]type, len)/************************************/s :=[] int {1,2,3 }            //直接初始化s := arr[:]                    //用数组初始化切片s := arr[startIndex:endIndex]  //新切片fmt.Printf("slice=%v\n",x)     //输出切片2种方法 结果:slice=[0 0 0]fmt.Println("slice=", x)func printSlice(x []int){      //这个函数用于输出切片信息   fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)}if(numbers == nil){            //判断空切片      fmt.Printf("切片是空的")}

Slice interception

package mainimport "fmt"func main() {   /* 创建切片 */   numbers := []int{0,1,2,3,4,5,6,7,8}      printSlice(numbers)   /* 打印原始切片 */   fmt.Println("numbers ==", numbers)   /* 打印子切片从索引1(包含) 到索引4(不包含)*/   fmt.Println("numbers[1:4] ==", numbers[1:4])   /* 默认下限为 0*/   fmt.Println("numbers[:3] ==", numbers[:3])   /* 默认上限为 len(s)*/   fmt.Println("numbers[4:] ==", numbers[4:])   numbers1 := make([]int,0,5)   printSlice(numbers1)   /* 打印子切片从索引  0(包含) 到索引 2(不包含) */   number2 := numbers[:2]   printSlice(number2)   /* 打印子切片从索引 2(包含) 到索引 5(不包含) */   number3 := numbers[2:5]   printSlice(number3)}func printSlice(x []int){   fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)}

Slice append () and copy ()

   var numbers []int   /* 允许追加空切片 */   numbers = append(numbers, 0)   /* 向切片添加一个元素 */   numbers = append(numbers, 1)   /* 同时添加多个元素 */   numbers = append(numbers, 2,3,4)   /* 创建切片 numbers1 是之前切片的两倍容量*/   numbers1 := make([]int, len(numbers), (cap(numbers))*2)   /* 拷贝 numbers 的内容到 numbers1 */   copy(numbers1,numbers)

Go language Range (range)

//range一个切片,返回下标和对应项nums := []int{2, 3, 4}sum := 0for _, num := range nums {  sum += num}    //range也可以用在map的键值对上。    kvs := map[string]string{"a": "apple", "b": "banana"}    for k, v := range kvs {        fmt.Printf("%s -> %s\n", k, v)    }    //range也可以用来枚举Unicode字符串。    //第一个参数是字符的索引,第二个是字符(Unicode的值)本身。    for i, c := range "go" {        fmt.Println(i, c)    }    //结果:    0 103    1 111    

Go language Map (collection)

Map is a collection of unordered key-value pairs. The map is unordered, and we cannot determine its return order, because the map is implemented using a hash table.

/* 声明变量,默认 map 是 nil ,nil map 不能用来存放键值对*/var myname map[ktype]vtype/* 使用 make 函数,之后才能添加元素 */myname = make(map[ktype]vtype)
//例子   var countryCapitalMap map[string]string   /* 创建集合 */   countryCapitalMap = make(map[string]string)      /* map 插入 key-value 对,各个国家对应的首都 */   countryCapitalMap["France"] = "Paris"   countryCapitalMap["Italy"] = "Rome"   countryCapitalMap["Japan"] = "Tokyo"   countryCapitalMap["India"] = "New Delhi"      /* 使用 key 输出 map 值 */   for country := range countryCapitalMap {      fmt.Println("Capital of",country,"is",countryCapitalMap[country])   }      /* 查看元素在集合中是否存在 */   captial, ok := countryCapitalMap["United States"]   /* 如果 ok 是 true, 则存在,否则不存在 */   if(ok){      fmt.Println("Capital of United States is", captial)     }else {      fmt.Println("Capital of United States is not present")    }

Delete element in map

//delete(), 参数为 map 和其对应的 key/* 删除元素 */delete(countryCapitalMap,"France");

Go language type Conversion

type(myname)   var a int = 17   var b int = 5   var c float32      c = float32(a)/float32(b)   fmt.Printf("c 的值为: %f\n",c)

Go language New

Go provides two distribution primitives, the built-in function and the new make .

New does not initialize memory, only 0 of memory is placed . That is, the new(T) T new item of type is assigned a zero memory space and returns its address, which is a *T value of type.

Go language Make

make(T,  ) The purpose of the built-in function args is different new(T) .

It is used only to create slices, mappings, and channels, and returns T *T a value that is initialized (rather than 0 ) of the type, rather than the. The reason for this difference is that these three types are essentially reference data types that must be initialized before they are used.

makeApplies only to mappings, slices, and channels and does not return pointers. To get an explicit pointer, use new allocated memory (below).

var p *[]int = new([]int)       // 分配切片结构;*p == nil;基本没用var v  []int = make([]int, 100) // 切片 v 现在引用了一个具有 100 个 int 元素的新数组// 没必要的复杂:var p *[]int = new([]int)*p = make([]int, 100, 100)// 习惯用法:v := make([]int, 100)

Go Error Handling

The Go language provides a very simple error handling mechanism through the built-in error interface.

We can generate error messages in the code by implementing the error interface type.

The function usually returns an error message in the final return value.

The error type is an interface type, which is its definition:

type error interface {    Error() string}
package mainimport ("fmt")// 定义一个 DivideError 结构type DivideError struct {dividee intdivider int}// 实现`error`接口func (de *DivideError) Error() string {strFormat := `Cannot proceed, the divider is zero.dividee: %ddivider: 0`return fmt.Sprintf(strFormat, de.dividee)}// 定义 `int` 类型除法运算的函数func Divide(varDividee int, varDivider int) (result int, errorMsg string) {if varDivider == 0 {dData := DivideError{dividee: varDividee,divider: varDivider,}errorMsg = dData.Error()return} else {return varDividee / varDivider, ""}}func main() {// 正常情况if result, errorMsg := Divide(100, 10); errorMsg == "" {fmt.Println("100/10 = ", result)}// 当被除数为零的时候会返回错误信息if _, errorMsg := Divide(100, 0); errorMsg != "" {fmt.Println("errorMsg is: ", errorMsg)}}

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.