声明语法 Declaration syntax
The style of language used to creat new varaible, types, functions, etc.
与传统的声明方式不同
x int
p *int
a [3]int
处理复杂的语法情况会比较方便阅读。
问题: Which language's declaration syntax reads like English from left-to-right?
答: Go
比如:
Go 可以把函数当作一个类型放入函数的输入变量中,比如下方的 func(int, int) int
,这是一个 input parameter type, 一个输入变量声明。
f func(func(int, int) int, int), int
这段代码有英语表达是: A function named 'f' that takes a function and an int as arguments and return an int.
Memory & code
In Go, varaibles are passed by vallue not reference.
func wrongExample() {
x := 5
increment(x)
fmt.Println(x)
/*
stiull prints 5
because the increment function
received a copy of x
*/
}
func increment(x int) {
x++
}
func goodExample() {
x := 5
x = increment(x)
fmt.Println(x) // Correct answer as 6
}
func increment(x int) int {
x++
return x
}