gpt4 book ai didi

loops - 如何在 for 循环中基于结构声明变量

转载 作者:行者123 更新时间:2023-12-02 23:00:12 24 4
gpt4 key购买 nike

这是一个在 for 循环之前声明变量的工作程序。

package main

import "fmt"

type brackets struct {
ch string
pos int
}

type stack []brackets

func main() {
p := brackets{ch: "a"}
st := make(stack,0)
for i := 0; i < 3; i++ {
p = brackets{ch: "a", pos: 1}
st = append(st, p)
fmt.Println(p)
fmt.Println(st)
}
}

我想声明相同的变量作为 for 循环的一部分。如何?这是一个错误的尝试。

package main

import "fmt"

type brackets struct {
ch string
pos int
}

type stack []brackets

func main() {
// p := brackets{ch: "a"}
// st := make(stack,0)
for st, p, i := make(stack,0), brackets{ch: "a"}, 0; i < 3; i++ {
p = brackets{ch: "a", pos: 1}
st = append(st, p)
fmt.Println(p)
fmt.Println(st)
}
}

我收到以下错误:语法错误:st, p, i := make(stack, 0),括号用作值

我很困惑,因为声明整数和字符串等标准类型非常容易。为什么不是我的结构?

最佳答案

composite literal section of the specification说:

A parsing ambiguity arises when a composite literal using the TypeName form of the LiteralType appears as an operand between the keyword and the opening brace of the block of an "if", "for", or "switch" statement, and the composite literal is not enclosed in parentheses, square brackets, or curly braces. In this rare case, the opening brace of the literal is erroneously parsed as the one introducing the block of statements. To resolve the ambiguity, the composite literal must appear within parentheses.

通过在复合文字周围添加括号来修复代码:

for st, p, i :=  make(stack,0), (brackets{ch: "a"}), 0; i < 3; i++ {
p = brackets{ch: "a", pos: 1}
st = append(st, p)
fmt.Println(p)
fmt.Println(st)
}

Run it on the playground .

关于loops - 如何在 for 循环中基于结构声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59336045/

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