读书笔记golang
go grammer
the standard Go compiler and gccgo both don't allow local variables declared but not used. Package-level variables have no such limit. If a local variable is only ever used as destination values, it will also be viewed as unused.
- Overflows are not allowed for typed constant values but are allowed for non-constant and untyped constant values.
- Non-constant integer values can be converted to strings.
- Non-constant floating-point and integer values can be explicitly converted to any other floating-point and integer types.
- Non-constant complex values can be explicitly converted to any other complex types.
The name of the folder of a package is not required to be the same as the package name. However, for a library package, it will make package users confused if the name of the package is different from the name of the folder of the package.
- A package-level variable is initialized after all of its depended variables.
- All package-level variables declared in a package are initialized before any
init
function declared in the same package is invoked. - All init functions in all involved packages in a program will be invoked sequentially. An init function in an importing package will be invoked after all the init functions declared in the dependency packages of the importing package for sure. All init functions will be invoked before invoking the main entry function.
The expressions enclosed within the body of an anonymous function call, whether the call is a general call or a deferred/goroutine call, will not be evaluated at the moment when the anonymous function call is invoked.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19package main
import "fmt"
func main() {
func() {
for i := 0; i < 3; i++ {
defer fmt.Println("a:", i)
}
}()
fmt.Println()
func() {
for i := 0; i < 3; i++ {
defer func() {
fmt.Println("b:", i)
}()
}
}()
}output is: a: 2 a: 1 a: 0
b: 3 b: 3 b: 3
to get b: 2, b: 1, b: 0
1
2
3
4
5
6
7func() {
for i := 0; i < 3; i++ {
defer func(i int) {
fmt.Println("b:", i)
}(i)
}
}()
go 数组大小不能超过2GB
需要针对数组元素的类型大小计算数组的最大长度范围 ([]uint8 最大2GB, []uint16 最大1GB,以此类推),但是 []struct{} 数组的长度可以超过2GB
goroutine
- 首先系统级的线程创建会创建默认大小的栈(一般默认可能为2Mb),主要用于保存递归函数调用的参数以及局部变量,默认大小的栈存在可能空间浪费或者栈不足的问题;而goroutine采用可以动态增减的栈,初始创建栈大小为(2kb或者4kb),根据需要动态增减(主流实现的栈大小可以达到1gb)