gpt4 book ai didi

go - Go 中的元组赋值

转载 作者:IT王子 更新时间:2023-10-29 00:57:20 24 4
gpt4 key购买 nike

来自 spec :

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. For instance, if f is a function returning two values, x, y = f() assigns the first value to x and the second to y. 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 the left-to-right order.

使用 this代码(i, n = i+2, n-1 inside for loop):

package main

import (
"fmt"
"math"
)

func main() {
p := &Prime{}
p.Generate(1000000)
fmt.Println(p.Last()) // 15485863
}

func (p *Prime) Generate(n uint) {
p.Primes = make([]uint64, 1, n)
p.Primes[0] = 2
next:
for i := uint64(3); n > 1; i, n = i+2, n-1 {
q := uint64(math.Sqrt(float64(i)))
for _, v := range p.Primes[1:] {
if v > q {
break
}
if i%v == 0 {
continue next
}
}
p.Primes = append(p.Primes, i)
// n--
}
}

type Prime struct {
Primes []uint64
}

func (p *Prime) Last() uint64 {
return p.Primes[len(p.Primes)-1]
}

输出是:

1999993

是一个正确的结果。

还有这段代码:

func (p *Prime) Generate(n uint) {
p.Primes = make([]uint64, 1, n)
p.Primes[0] = 2
next:
for i := uint64(3); n > 1; i += 2 {
q := uint64(math.Sqrt(float64(i)))
for _, v := range p.Primes[1:] {
if v > q {
break
}
if i%v == 0 {
continue next
}
}
p.Primes = append(p.Primes, i)
n--
}
}

输出是正确的:

15485863

go版本go1.11.5 linux/amd64

我在元组 Assignments 上遗漏了什么吗?在围棋中?

提前致谢。

最佳答案

不,给出错误结果的不是元组赋值。

这两个代码之间存在细微差别,这导致了错误。在 playgound 代码中,i,n = i+2,n-1 使 n = n-1 在每次循环迭代时运行,而 github 代码只运行 n = n-1i 是质数时(如果 continue next 运行,它会跳过 n--)。

关于go - Go 中的元组赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54726660/

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