Golang Getting Started - Basic Types & function definition articles

About the configuration and output in the previous article, then we enter the next step of learning

Preface: Go language features

Go Google language is a static developed, compiled and concurrent garbage collection and comes into language.
Go language style is similar to the C language, the syntax has been greatly optimized on the basis of the C language, remove unwanted expression in parentheses, and only for the cycle way of saying, you can adapt the traversal value, key, etc. Therefore, Go language is very easy to get started.
Go language most distinctive characteristic than goroutine. Go language can be implemented in the language of the function layer by goroutine concurrent parallel. goroutine similar thread, but not thread goroutine will automatically scheduled in the Go language runtime. Therefore, the Go language is well suited for the preparation of highly concurrent network services.

A, Go and use of basic grammar

1, integer type

Go对类型的长度有极大要求
长度类型:int8 int16 int32 int64
对应无符号类型:uint8 uint16 uint32 uint64

2, float

Go语言支持两种浮点整数:
float32:最大范围约为 3.4e38,可以使用常量定义:math.MaxFloat32
float64:最大范围约为 1.8e308,可以使用常量定义:math.MaxFloat64

3, Boolean

布尔型数据只有true和false
Go语言中不允许将整型强制转换为布尔型,代码如下:
fmt.Println(int(n) * 2)
编译错误,输出如下:
cannot convert n (type bool) to type int
布尔型无法参与数值运算,也无法与其他类型进行转换

4, string

For string type, double quotes is enlarged compared to live string type, it can be placed in a non-ASCII character

str := "hello world"
ch  := "中文"

5, sliced

Next, about the Go language sections (can be dynamically allocated space) with the same type of elements is a variable-length sequence

var arr[]类型    // 初始化的时候定义,后面追加上类型 如int string float等
例:var arr[]int

Elements in the slice using "[]" to access, providing a numeric index in [] may be acquired value value corresponding slice index default access is zero, there is no default value from the corresponding figure start of such assignment is defined as 0, the following code is affixed

// 创建切片
item := make([]int, 3)	//创建一个容量为3的整型切片 ps:其实就是创建一个容量只能为3的切片,但是value都只能为int
item[0] = 0		//为切片元素赋值
item[1] = 1
item[2] = 2

fmt.Println(item)
输出:[0 1 2]

The assignment of sequence to

// 创建切片
item := make([]int, 10)	//创建一个容量为10的整型切片 ps:其实就是创建一个容量只能为10的切片,但是value都只能为int
item[7] = 77
item[8] = 88

fmt.Println(item)
输出:[0 0 0 0 0 0 0 77 88 0]  // 未定义的索引值则默认为0

We can also be sliced ​​additional (append)

info := append(item, 99)

fmt.Println(item, info)
输出: [0 0 0 0 0 0 0 77 88 0 99]  // 在原来的基础上追加了99

Alternatively covering (copy)

test := []int{1,2,3,4,5}
copy(info, test)

fmt.Println(info)
输出:[1 2 3 4 5 0 0 77 88 0 99]

String can also follow the sliced ​​manner (string interception function, bit number 1 from the beginning)

str := "hello world"
fmt.Println(str[6:])// 输出截取,这里注意的是截取只能截取字符串类型的,其他类型截不了
输出:world

These are simply some small cases, there are some more tips grammatical function, available on the official document viewing Go http://docscn.studygolang.com/doc/

Second, variable

1, variable declaration

var a int//声明一个整型类型的变量,可以保存整数数值
var b string//声明一个字符串类型的变量
var c []float32//声明一个32位浮点切片类型的变量,浮点切片表示由多个浮点类型组成的数据结构
var d func() bool//声明一个返回值为布尔类型的函数变量,这种形式一般用于回调函数,即将函数以变量的形式保存下来,在需要的时候重新调用这个函数
var e struct{//声明一个结构体变量,拥有一个整型的x字段
    x int
}

Standard definitions: var parameters type

Batch Statement

var (
a int 
b string
c []float32
d func() bool
e struct{
    x int
    }
)

Initialized variable (standard format)

var 变量名 类型 = 表达式
例:小明考试考了100分
var score int = 100

Initialize variables (short variable declaration)

score := 100
// 如果score已经被var初始化过,则这个时候会报错,例如以下
var score int = 90
score := 80
// error : no new variables on left side of :=
// 报错提示的原因是左边没有新的变量名出现,则不允许重新赋值

// ps:也可以支持多个变量一直赋值
info, score, x = 0, 1, 2

2, the anonymous variable (not a variable name and not need to use, can reduce the memory space)

During development, the sometimes call a method, found that some of the parameters is not needed, but do not want to pick up waste memory receive, you can use the "_" be replaced by an underscore

func item() (int,int) {
    return 100, 200
}
a, _ := item()
fmt.Println(a)

输出:100

// 当然,我们也可以在赋值的时候这么做

_, score := 0, 80
fmt.Println(score)

输出:80

Go in memory that is still very strong, nothing to worry about running out of memory, it can safely ease of use

Third, function

Conventionally defined function

func 方法名(参数列表) 返回值 {
    定义
}

例:

func item(a) int {
    return 100
}

1, the value of the function (closure)

Function value is not just a string of codes, also recorded state. Go use closures (Closures) technology function value, the function value Go programmer called the closure. We look at an example of closures:

func f1(limit int) (func(v int) bool) {
    //编译器发现limit逃逸了,自动在堆上分配
    return func (v int) bool { return v > limit}
}
func main(){

    closure := f1(3)
    fmt.Printf("%v\n", closure(1)) //false
    fmt.Printf("%v\n", closure(3)) //false
    fmt.Printf("%v\n", closure(10)) //true
}

ps:程序执行流程

1、程序进入main后,发现调用了f1方法并带入了”3“,此时返回一个闭包
2、走到下面closure(1)时,程序发现有传入闭包值”1“
3、程序走进上面的方法内,此时limit = 3, 闭包内的v = 1
4、走到下面的逻辑判断中,引用闭包内的v,并且将v与limit做比较
5、最终得到结果,返回给下面的 fmt.Printf("%v\n", closure(1))进行输出
6、依次类推

Function of the variable parameters

The variable parameters, i.e. the parameter value is not a fixed dead, can have an unlimited number N, e.g., as a function fmt.Printf, but only the last parameter can be set to a variable parameter

statement

func 函数名(变量名...类型) 返回值

For example:

func getData(str string, vals... int) (num int) {
    for  _,v := range vals {
	num += v
    }
    num += len(str)
    return
}

func main(){
    fmt.Printf("%d\n", getData("abc", 1,2,3,4,5 )) 
}

输出:18


将传入的1,2,3,4,5 循环追加给num值,最后再加上str的长度 15 + 3 = 18
注意:在for后面一点要加上匿名函数,否则始终不会循环追加最后一个值,如去掉加起来则为13
getData第二个参数即最后一个参数则为可变参数

2, the delay function is performed defer

It contains defer sentence after (such as return, panic) function is finished, before the release of the stack calls are declared defer statement , commonly used in the release of resources, time-consuming functions such as recording, it has the following characteristics:

  • When defer is declared, the parameters will be resolved in real time
  • Reverse order and declaration order
  • The return value can be read defer known
//演示defer的函数可以访问返回值
func f2() (v int) {
    defer func (){ v++}()
    return 1 //执行这个时,把v置为1
}

//演示defer声明即解释
func f3(i int) (v int) {
    defer func(j int) {
	v+= j
    } (i) 		//此时函数i已被解析为10,后面修改i的值无影响
    v = 9		// v = 9
    i = i*2		// i = 20
    return
}

//演示defer的执行顺序,与声明顺序相反
func f4() {
    defer func() {fmt.Printf("first\n")} ()
    defer func() {fmt.Printf("second\n")} ()
}

func main(){
    fmt.Printf("%d\n", f2()) // 13
    fmt.Printf("%d\n", f3(10)) // 19
    f4() //second\nfirst\n

最终输出:
        2
        19
        second
        first

执行过程:
1、首先调用了f2,由于defer是在return执行后再去执行的,所以当return 1时,附加v++ 所以最终返回值为2
2、调用了f3并传入值为10,进入到f3方法中,v = 9,i = 20,走到defer,此时i已经被解析成了10,所以后面的相乘无影响
3、接着进入defer后,设定了j值,此时j = i = 10,v是后面新赋的值,也没有被解析,所以v+=j 则等于 v = 9+10 = 19,最后返回19
4、最后一步f4是返回的顺序是相反的,则验明了defer是在声明的倒序执行的

ps:一般典型的用来计算耗时,资源关闭等,相关操作可按照业务逻辑编写

Golang study articles will continue to update, thank you

 

 

Published 59 original articles · won praise 219 · Views 100,000 +

Guess you like

Origin blog.csdn.net/qq_34284638/article/details/104898402