我想知道为什么这两种方式的结果不同
时间:2024-02-19
浏览:279
作者:佚名
今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《我想知道为什么这两种方式的结果不同》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!
问题内容
func main() {
var a int = 10
var b int = 20
swap(&a,&b)
fmt.Println(a,b)
var c int = 10
var d int = 20
swap2(&c,&d)
fmt.Println(c,d)
}
func swap(x, y *int) {
*x = *y
*y = *x
}
func swap2(x, y *int) {
*x,*y= *y,*x
}
//我想知道为什么这两种方式结果不同
//20 20
//20 10
解决方案
swap2(&c,&d) 导致 c 和 d 被设置为不同值的原因是因为该函数由单个赋值语句组成,而 swap(&a,&b) 由两个赋值语句组成。 go 中的赋值语句有特定的求值顺序。来自language specifications:
考虑到这一点,我们来注释 swap(x, y *int):
// x points to an int with value 10, // y points to an int with value 20. *x = *y // 1. *y = *x // 2.
第一个赋值语句首先出现,所以这样做:
// x points to an int with value 10, // y points to an int with value 20. *x = *y // 1. (value of int pointed to by x) = (value of int pointed to by y) // now x points to an int with value 20. *y = *x // 2.
第一个赋值语句完成后,运行第二个赋值语句:
// x points to an int with value 10, // y points to an int with value 20. *x = *y // 1. (value of int pointed to by x) = (value of int pointed to by y) // now x points to an int with value 20. *y = *x // 2. (value of int pointed to by y) = (value of int pointed to by x) // now y points to an int with value 20.
但是,因为 swap2 仅使用单个赋值语句,所以我们必须小心发生的顺序。规范规定左侧的指针间接和右侧的表达式同时求值:
// x points to an int with value 10 // y points to an int with value 20 *x,*y = *y,*x // 1. (value of int pointed to by x), (value of int pointed to by y) = 20, 10
其次,分配是按从左到右的顺序进行的。但因为我们已经评估了语句的右侧,所以这些只是值。
// x points to an int with value 10 // y points to an int with value 20 *x,*y = *y,*x // 1. (value of int pointed to by x), (value of int pointed to by y) = 20, 10 // 2. now x points to an int with value 20, y points to an int with value 10
换句话说,swap2 与此函数执行相同的操作:
swap3(x, y *int) {
valueX := *x
valueY := *y
*x = valueY
*y = valueX
}
swap2形式的优点是函数不会显式分配不必要的临时变量。
以上就是《我想知道为什么这两种方式的结果不同》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
