Go Basic
[TOC]
GO简单用法
GO Basics
Functions continued
When two or more consecutive named function parameters share a type, you can omit the type from all but the last.
In this example, we shortened
x int, y int
to
x, y int
package main
import "fmt"
func add(a, b int) int {
return a + b
}
func main(){
fmt.Println(add(42, 34))
}
Multiple results
a function can return any number of results
a swap function returns two strings.
package main
import "fmt"
func swap(x, y string) (string, string){
return y,x
}
func main(){
fmt.Println(swap("hello", "world"))
}
Named return values 命名返回值
Go’s return values may be named. If so, they are treated as variables defined at the top of the function.
These names should be used to document the meaning of the return values.
A return statement without arguments returns the named return values. This is known as a “naked” return.
Naked return statements should be used only in short functions, as with the example shown here. They can harm readability in longer functions.
package main
import "fmt"
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
func main() {
fmt.Println(split(17))
}
Variables 变量
The var statement declares a list of variables; as in function argument list, the type is last.
A var statement can be at the package or function level.We see both in this example.
package main
import "fmt"
var c, python, java bool
func main() {
var i int
fmt.Println(i, c, python, java)
}
Variables with initializers
A var declaration can include initializers, one per varialbe.
变量初始化,每个变量都要包含值。
If an initializer is present, the type can be omitted; the variable will take the type of initializer.
如果初始化变量了,可以省略类型。变量的类型会是初始值的类型。
package main
import "fmt"
var i, j int = 1, 2
func main() {
var c, python, java = "c", false, "no!"
fmt.Println(i, j, c, python, java)
}