Golang Notes
2 Program Structure2.1 Names
2.2 DeclarationsA declaration names a program entity and specifies some or all of its properties. Var/:=Varvar name type = expression
1.If the expression is omitted,the initial value is the zero value for the type:
2.function 内声明的var一定要用上,不然会报错;import的package一定要用上,不然会报错;const,type,func则不会发生上述问题。
var i,j,k int // ok
var i,k = true, 2.3,"four" // ok & type(j)为float64
var i bool,j float64,k string = true,"four" // error
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. i,j := 0, 1.0 // ok
2.声明语句中必须要有新变量声明 // 声明新变量 in,err
in,err := os.Open(infile)
// 声明新变量 out
out,err := os.Create(outfile)
// 而下面两个语句则不合法
f,err := os.Open(infile)
f,err := os.Create(outfile) // compile error: no new variables
// 应该改为
f,err = os.Create(outfile)
PointersA pointer value is the address of a variable. x := 1
p := &x
fmt.Println(*p) // "1"
*p = 2
fmt.Println(x) // "2"
1.一个被引用的局部变量,即使在函数调用后仍然不会被回收: var p = f()
fun f() *int{
v := 1
return &v
}
// Each call of f returns a distance value:
fmt.Println(f()==f()) // "false"
关于newAnother 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. p := new(int)
fmt.Println(*p) // "0"
*p = 2
fmt.Println(*p) // "2"
1.new不需要delete p := new(int)
q := new(int)
fmt.Println(p==q) // "false"
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 Variablesa package-level variable: the entire execution of the program (即使是被import的package中的package-level variable); 1.Golang的垃圾回收机制 2.Golang中variables哪些放在栈上,哪些放在堆上,不取决于它的声明方式是var还是new。 consttypefunc用例
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |