Go语言”奇怪用法“有哪些

Python020

Go语言”奇怪用法“有哪些,第1张

1,go的变量声明顺序是:”先写变量名,再写类型名“,此与C/C++的语法孰优孰劣,可见下文解释:

http://blog.golang.org/gos-declaration-syntax

2,go是通过package来组织的(与python类似),只有package名为main的包可以包含main函数,一个可执行程序有且仅有一个main包,通过import关键字来导入其他非main包。

3,可见性规则。go语言中,使用大小写来决定该常量、变量、类型、接口、结构或函数是否可以被外部包含调用。根据约定,函数名首字母小写即为private,函数名首字母大写即为public。

4,go内置关键字(25个均为小写)。

5,函数不用先声明,即可使用。

6,在函数内部可以通过 := 隐士定义变量。(函数外必须显示使用var定义变量)

7,go程序使用UTF-8编码的纯Unicode文本编写。

8,使用big.Int的陷阱:

http://stackoverflow.com/questions/11270547/go-big-int-factorial-with-recursion

9,从技术层面讲,go语言的语句是以分号分隔的,但这些是由编译器自动添加的,不用手动输入,除非需要在同一行中写入多个语句。没有分号及只需少量的逗号和圆括号,使得go语言的程序更容易阅读。

10,go语言只有一个循环结构——for循环。

11,go里的自增运算符只有——“后++”

12,go语言中的slice用法类似python中数组,关于slice的详细用法可见:http://blog.golang.org/go-slices-usage-and-internals

13,函数也是一个值,使用匿名函数返回一个值。

14,函数闭包的使用,闭包是一个匿名函数值,会引用到其外部的变量。

注:本文是对 golang-101-hacks 中文翻译。

在Go语言中,函数参数是值传递。使用slice作为函数参数时,函数获取到的是slice的副本:一个指针,指向底层数组的起始地址,同时带有slice的长度和容量。既然各位熟知数据存储的内存的地址,现在可以对切片数据进行修改。让我们看看下面的例子:

In Go, the function parameters are passed by value. With respect to use slice as a function argument, that means the function will get the copies of the slice: a pointer which points to the starting address of the underlying array, accompanied by the length and capacity of the slice. Oh boy! Since you know the address of the memory which is used to store the data, you can tweak the slice now. Let's see the following example:

运行结果如下

由此可见,执行modifyValue函数,切片s的元素发生了变化。尽管modifyValue函数只是操作slice的副本,但是任然改变了切片的数据元素,看另一个例子:

You can see, after running modifyValue function, the content of slice s is changed. Although the modifyValue function just gets a copy of the memory address of slice's underlying array, it is enough!

See another example:

The result is like this:

而这一次,addValue函数并没有修改main函数中的切片s的元素。这是因为它只是操作切片s的副本,而不是切片s本身。所以如果真的想让函数改变切片的内容,可以传递切片的地址:

This time, the addValue function doesn't take effect on the s slice in main function. That's because it just manipulate the copy of the s, not the "real" s.

So if you really want the function to change the content of a slice, you can pass the address of the slice:

运行结果如下

更多Go的相关文章发布在我的个人博客上,欢迎访问

www.guiguiyo.cn