在Go中交换变量值的最佳方法? [英] Best way to swap variable values in Go?
本文介绍了在Go中交换变量值的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以像在python中那样交换元素?
Is it possible to swap elements like in python?
a,b = b,a
还是我们必须使用:
temp = a
a = b
b = temp
推荐答案
是的,有可能.假设 a
和 b
具有相同的类型,那么提供的示例就可以正常工作.例如:
Yes, it is possible. Assuming a
and b
have the same type, the example provided will work just fine. For example:
a, b := "second", "first"
fmt.Println(a, b) // Prints "second first"
b, a = a, b
fmt.Println(a, b) // Prints "first second"
这既合法又惯用,因此不需要使用中间缓冲区.
This is both legal and idiomatic, so there's no need to use an intermediary buffer.
这篇关于在Go中交换变量值的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文