2 Program Structure
2.1 Names
可见性
命名风格
写短语要么全部大写。要么全部小写。比如htmlEscape,HTMLEscape,不能写成HtmlEscape。
2.2 Declarations
A declaration names a program entity and specifies some or all of its properties.
There are four major kinds of declarations: var,const,type and func.
Var/:=
Var
1.If the expression is omitted,the initial value is the zero value for the type:
Type | Zero Value |
---|---|
numbers | 0 |
boolean | 0 |
strings | “” |
interfaces | nil |
reference types (slice,pointer,map,channel,function) | nil |
aggregate types (array,struct) | the zero value of all of its elements or fields |
2.function 内声明的var一定要用上,不然会报错;import的package一定要用上,不然会报错;const,type,func则不会发生上述问题。
-
3.
Short Variable Declarations (:=)
Within a function,an alternate form called a short variable declaration may be used to declare and initialize local variables.
- name := expression
1.
2.声明语句中必须要有新变量声明
Pointers
A pointer value is the address of a variable.
Pointer就是address的Type。
- copy a reference types (pointer,slices,maps and channels) <=> create new aliases or ways to identify the same variable.
关于new
Another way to create a variable is to use the built-in function new. The expression new(T) creates an unnamed variable of type T,initializes it to the zero value of T,and returns its address,which is a value of type *T.
1.new不需要delete
2.Each call to new return a distinct variable with a unique address. However,there is one exception to this rule: two variables whose type carries no information and is therefore of size zero,such as struct{} or [0]int,may,depending on the implementation,have the same address.
3.The new function is relatively rarely used because the most common unnamed variables are of struct types,for which the struct literal Syntax is more flexible.
Lifetime of Variables
a package-level variable: the entire execution of the program (即使是被import的package中的package-level variable);
a local variable have dynamic lifetime: a new instance is created each time the declaration statement is executed,and the variable lives on until it becomes unreachable,at which point its storage may be recycled.
1.Golang的垃圾回收机制
2.Golang中variables哪些放在栈上,哪些放在堆上,不取决于它的声明方式是var还是new。
const
type
func
用例
- 读取/设置命令行的flags以及arguments。(P33)