go语言基础之匿名变量和多重赋

1、匿名变量

package main //必须有一个main包

import "fmt"

func test() (a, b, c int) {
	return 1, 2, 3
}

func main() {
	var c, d, e int
	c, d, e = test() //return 1, 2, 3
	fmt.Printf("c = %d, d = %d, e = %d\n", c, d, e)
   
     //_匿名变量,丢弃数据不处理, 
	 //_匿名变量配合函数返回值使用,才有优势
	_, d, _ = test()
	fmt.Printf("d = %d\n", d)
}

#执行结果:

c = 1, d = 2, e = 3

#只取d的值 d = 2

2、多重赋值

示例1:

package main //必须有一个main包

import "fmt"

func main() {
	a, b := 10, 20
	var tmp int
	a = b
	b = tmp
	fmt.Printf("a = %d, b = %d\n", a, b)
}

#执行结果:

a = 20, b = 0

示例2:

package main //必须有一个main包

import "fmt"

func main() {
	i, j := 10, 20
	i, j = j, i
	fmt.Printf("i = %d, j = %d\n", i, j)
}

#执行结果: 

i = 20, j = 10

  

 

posted @ 2018-12-30 14:34  努力哥  阅读(458)  评论(0编辑  收藏  举报