Go fast and simple language entry (a)

I summed up some of the points of concern when I go to see the language, suitable for a person based on exchange

! ! If you want to go quickly understand code, you can look down, if you want the system to learn the language suggest that you can go see https://www.jianshu.com/p/5ee783bbdcac ! !

First, the variable declaration
var variable name variable type
var (
variable name Variable type
Variable name Variable type
Variable name Variable type
)

	指针: var 变量名 new(类型名)
	数组: var 变量名 []类型名
	结构体: 实例名 struct{
		变量名 变量类型
	}

Second, variable initialization
var aaa = 40 // 40 The compiler will guess your aaa type
var damageRate float32 = 0.17 // normal assignment
aaa: = 40 // simpler wording, no formal definition of what aaa,: = on define the equivalent of an assignment,

	1.已定义过的变量不能用 := 进行赋值
	2.:= 可以一次性定义多个变量并赋值 
		eg. 	conn, err := net.Dial("tcp", "127.0.0.1:8080")
				conn2, err := net.Dial("tcp", "127.0.0.1:8080")
		net.Dial 返回了两个值,分别赋值给了 conn和err。
		(conn, err) 和 (conn2, err) , 这两组变量,只要每组有一个是新变量就可以通过,编译器不会报错
	3.多变量赋值 func (p IntSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
		这个例子就很直观了,多变量赋值从左到右依次赋值,并不care你是谁

	4. 对函数定义有疑问的,看看下面几个例子应该就差不多了
	type IntSlice []int
	func (p IntSlice) Len() int           { return len(p) }
	func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
	func (p IntSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
	作用范围不止在函数里面的放到前面括号里,作用范围只在函数里面的放到后面括号里

	5.匿名变量 _,b := GetData()  不在乎这个变量是谁,用_占个位置就行
	如果只需要前面的变量  a := GetData() 就行

Third, the string
str: = "escape character string note on the line."

	1.utf8编码
	2.多行字符串输入
		ch := ` 第一行
		第二行
		第三行
		`
		两边加的这个是反引号,键盘1旁边那个

Fourth, the character
uint8 byte is equivalent to
Rune equivalent to Int32, representative of a UTF-8 character. When you need to handle Chinese, Japanese or other complex characters, you need to use the rune type.

Five cast
var C = float32 Math.PI
fmt.Println (int (C))

别的转换方式 fmt.Printf("int32: 0x%x %d\n", c, c)

Sixth, the pointer
var A = 111
PTR: // A = & defined
value: = * ptr // references

	1.有指针的交换函数就要借助中间变量,不能再像 【二、3 】 说明的那样直接赋值
	2.创建指针的另一种方式 var ptr=new(int)

Seven variables escape
simple terms, this variable does not exist anymore, but you still use him, then the variable is a variable escape

package main

import "fmt"

// 声明空结构体测试结构体逃逸情况
type Data struct {
}

func dummy() *Data {

    // 实例化c为Data类型
    var c Data

    //返回函数局部变量地址
    return &c
}

func main() {

    fmt.Println(dummy())
}

For example, in the above example c pointer, the original C program, there has been cross-border visits, but go there to escape the variables, we succeeded to escape c pointer
variable escape not just the pointer type, if the above return c, integer, then c is a variable escape to the heap memory

Eight, const
very simple
const AA 1 =
const (
AA = 1
bb = 2
)

The following give an example analog enumeration class const

type Weapon int

const (
     Arrow Weapon = iota    // 开始生成枚举值, 默认为0
     Shuriken
     SniperRifle
     Rifle
     Blower
)

// 输出所有枚举值
fmt.Println(Arrow, Shuriken, SniperRifle, Rifle, Blower)

// 使用枚举类型并赋初值
var weapon Weapon = Blower
fmt.Println(weapon)
const (
    FlagNone = 1 << iota
    FlagRed
    FlagGreen
    FlagBlue
)
fmt.Printf("%d %d %d\n", FlagRed, FlagGreen, FlagBlue)
fmt.Printf("%b %b %b\n", FlagRed, FlagGreen, FlagBlue)

Results The above example is 2,4,8 (0b1,0b10,0b100)

	上面例子引申出 type 定义:
	go1.9 之前  type byte uint8
	go1.9 之后  type byte=uint8
	值得注意的是 重定义的类型必须是本地类型,import的包里面的类型不能起别名

IX array
var Team [. 3] String
Team [0] = "Hammer"
...

var team = [...] string { "hammer", "soldier", "mum"} //! ! Here ... it means that the compiler can figure array size

Array traversal function

var team [3]string
team[0] = "hammer"
team[1] = "soldier"
team[2] = "mum"

for k, v := range team {
    fmt.Println(k, v)
}

K is the traversal key array index value of each element of an array of value v.
This range, no contact will really be faint head high, detailed recommendations https://www.jianshu.com/p/4205659ca419 , is simply a built-in function to traverse

Ten, sliced

var highRiseBuilding [30]int

for i := 0; i < 30; i++ {
        highRiseBuilding[i] = i + 1
}

// 区间
fmt.Println(highRiseBuilding[10:15])

// 中间到尾部的所有元素
fmt.Println(highRiseBuilding[20:])

// 开头到中间的所有元素
fmt.Println(highRiseBuilding[:2])

Code results

[11 12 13 14 15]
[21 22 23 24 25 26 27 28 29 30]
[1 2]

A = var [] {l, 2,3}
A [:] // original slice l, 2,3} {
A [0: 0]} // {

  1. make Constructor sliced

    make ([] T, size, cap) // default can size, CAP
    T: element type slice.
    size: the number of elements is allocated for this type.
    cap: the number of elements pre-allocated, this does not affect the size after the value is set, only able to allocate space in advance, reduce performance problems caused by multiple distribution space.

  2. append () to add elements to slice

team := []string{"Pig", "Flyingcake", "Chicken"}
car = append(car, team)
  1. copy (): Slice copy
    refData: srcData // reference =
    Copy (copyData, srcData) // copy the data to the new slice space
    copy (copyData, srcData [4: 6]) // Copy part

  2. Slice delete
    Here Insert Picture Description
    eleven, the Map Mapping

scene := make(map[string]int)

scene["route"] = 66
scene["brazil"] = 4
scene["china"] = 960

for k, v := range scene {
    fmt.Println(k, v)
}
  • make (map [keyType] valueType, cap), keyType represents a bond type, valueType a value indicating the type
  • map does not need to recover, you can directly make a new
  • sync.Map
    concurrent access map need to lock, go provides sync.Map, people do not need to manually write code lock, his own internal maintenance, the following is the specific implementation
package main

import (
      "fmt"
      "sync"
)

func main() {

    var scene sync.Map

    // 将键值对保存到sync.Map
    scene.Store("greece", 97)
    scene.Store("london", 100)
    scene.Store("egypt", 200)

    // 从sync.Map中根据键取值
    fmt.Println(scene.Load("london"))

    // 根据键删除对应的键值对
    scene.Delete("london")

    // 遍历所有sync.Map中的键值对
    scene.Range(func(k, v interface{}) bool {

        fmt.Println("iterate:", k, v)
        return true
    })

}

Twelve, List
in the Go language, the list using the container / list package to achieve, achieve internal principle is doubly-linked list

	l := list.New()
	l.PushBack("fist")
	l.PushFront(67)
	l.InsertAfter("high", element)
    l.InsertBefore("noon", element)
    
    l.Remove(element) for i := l.Front(); i != nil; i = i.Next() {
   	 	fmt.Println(i.Value)
	}

Guess you like

Origin blog.csdn.net/LiuYangQ_Q/article/details/90677961