You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
```go
package main
import "fmt"
func main () {
/* 定义局部变量 */
var a int = 100
var b int = 200
fmt . Printf ( "交换前 a 的值为 : %d\n" , a )
fmt . Printf ( "交换前 b 的值为 : %d\n" , b )
/* 通过调用函数来交换值 */
swap ( a , b )
fmt . Printf ( "交换后 a 的值 : %d\n" , a )
fmt . Printf ( "交换后 b 的值 : %d\n" , b )
}
/* 定义相互交换值的函数 */
func swap ( x , y int ) int {
var temp int
temp = x /* 保存 x 的值 */
x = y /* 将 y 值赋给 x */
y = temp /* 将 temp 值赋给 y*/
return temp ;
}
```
上面代码a和b交换后不变, 因为是值传递, 需要修改为引用传递。修改swap函数,这里x和y变成了
指针变量, 相应的调用swap函数也需要传入内存地址`swap(& a,& b)`
```go
func swap ( x * int , y * int ) {
var temp int
temp = * x /* 保存 x 地址上的值 */
* x = * y /* 将 y 值赋给 x */
* y = temp /* 将 temp 值赋给 y */
}
```