gpt4 book ai didi

arrays - 试图添加到 slice 的索引超出范围

转载 作者:数据小太阳 更新时间:2023-10-29 03:40:37 24 4
gpt4 key购买 nike

var bar string
var i int
var a []string
for foo, _ := reader.NextWord(); foo != bar; foo, _ = reader.NextWord() {
bar = foo
fmt.Print(foo)
a[i] = foo
i++
}

这不应该是创建一个 nil slice ,然后将值添加到适当的位置吗?我一直在获取超出范围的索引,所以我认为它不会添加到 a[i]...

首先检查长度

if len(a) > 0 {
a[i] = foo
}

似乎有帮助,但没有得到我预期的结果。我会继续玩。

更新:我确实最终使用了附加...我打算更新这个线程,但谢谢你们。

package main

import (
"fmt"
"log"
"os"
"strings"

"github.com/steven-ferrer/gonsole"
)

func main() {
file, err := os.Open("test.txt")
if err != nil {
log.Println(err)
}
defer file.Close()

reader := gonsole.NewReader(file)

// cycle through
var bar string
var i int

var quality []string = make([]string, 0)
var tempName []string = make([]string, 0)
var name []string = make([]string, 0)

for foo, _ := reader.NextWord(); foo != bar; foo, _ = reader.NextWord() {
bar = foo

if strings.Contains(foo, "(normal)") {
quality = append(quality, "normal")
for state := 0; state < 1; foo, _ = reader.NextWord() {
if foo == "|" {
state = 1
}
tempName = append(tempName, foo)
}
nameString := strings.Join(tempName, "")
name = append(name, nameString)
} else if strings.Contains(foo, "(unique)") {
quality = append(quality, "unique")
for state := 0; state < 1; foo, _ = reader.NextWord() {
if foo == "|" {
state = 1
}
tempName = append(tempName, foo)
}
nameString := strings.Join(tempName, "")
name = append(name, nameString)
} else if strings.Contains(foo, "(set)") {
quality = append(quality, "set")
for state := 0; state < 1; foo, _ = reader.NextWord() {
if foo == "|" {
state = 1
}
tempName = append(tempName, foo)
}
nameString := strings.Join(tempName, "")
name = append(name, nameString)
}
if tempName != nil {
tempName = nil // clear tempName
}
i++
}

最佳答案

您的 slice a 需要使用 make 进行分配。

var a []string = make([]string, n)

其中 n 是 slice 的大小。

关于arrays - 试图添加到 slice 的索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54046974/

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