gpt4 book ai didi

pointers - 交换和元组分配的基本查询

转载 作者:IT王子 更新时间:2023-10-29 01:53:58 26 4
gpt4 key购买 nike

如果我想在 go 中交换两个变量的值,我会这样做

func swap(xPtr, yPtr *int) {
dummy := *xPtr
*xPtr = *yPtr
*yPtr = *xPtr
}

然而,最干净的解决方案是*xPtr, *yPtr = *yPtr, *xPtr。为什么这与计算有不同的效果

*xPtr = *yPtr                                                            
*yPtr = *xPtr

换句话说,从纯语法我理解如果*xPtr=1, *yPtr=2,那么两者都必须修改为 2,而不是像 *xPtr, *yPtr = *yPtr, *xPtr 那样修改为 2, 1

最佳答案

在 Go 中,交换只需写:

*xPtr, *yPtr = *yPtr, *xPtr

The Go Programming Language Specification

Assignments

A tuple assignment assigns the individual elements of a multi-valued operation to a list of variables. There are two forms. In the first, the right hand operand is a single multi-valued expression such as a function call, a channel or map operation, or a type assertion. The number of operands on the left hand side must match the number of values.

In the second form, the number of operands on the left must equal the number of expressions on the right, each of which must be single-valued, and the nth expression on the right is assigned to the nth operand on the left:

one, two, three = '一', '二', '三'

The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.


The assignment proceeds in two phases. First, the operands of pointer indirections on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.

例如,来回交换:

package main

import "fmt"

func main() {
xPtr, yPtr := new(int), new(int)
*xPtr, *yPtr = 1, 2
fmt.Println(*xPtr, *yPtr)

// Swap - idiomatic Go
*xPtr, *yPtr = *yPtr, *xPtr
fmt.Println(*xPtr, *yPtr)

// is equivalent to

// RHS - evaluate
ty := *yPtr
tx := *xPtr
// LHS - assign
*xPtr = ty
*yPtr = tx
fmt.Println(*xPtr, *yPtr)

// is equivalent to

// Optimized
t := *xPtr
*xPtr = *yPtr
*yPtr = t
fmt.Println(*xPtr, *yPtr)

// is not equivalent to

// Error: No swap
*xPtr = *yPtr
*yPtr = *xPtr
fmt.Println(*xPtr, *yPtr)
}

Playground :https://play.golang.org/p/Ph4Dsc_jsJJ

输出:

1 2
2 1
1 2
2 1
1 1

关于pointers - 交换和元组分配的基本查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51182049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com