gpt4 book ai didi

list - 为什么将列表整数元素转换为字符串时得到 "interface conversion: interface is int32"?

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

Go 新手...我编写了一个程序来删除存储在列表中的重复整数。当我为 removeDuplicates 函数运行以下测试时,我收到以下指向此行的错误:linked_test 中的 testString += strconv.Itoa(e.Value.(int))。去吧。为什么会这样,我该如何解决?我将整数存储在 testList 中并使用 e.Value 获取它们并使用 .(int) 进行类型转换。

panic: interface conversion: interface is int32, not int [recovered]
panic: interface conversion: interface is int32, not int

linked_test.go

package linked

import (
"container/list"
"strconv"
"testing"
)

func TestDuplicates(t *testing.T) {
var (
testList = list.New()
exampleList = list.New()
testString string = ""
)
testList.PushBack(1)
testList.PushBack(2)
testList.PushBack(3)
testList.PushBack(2)
exampleList = removeDuplicates(testList)
for e := exampleList.Front(); e.Next() != nil; e = e.Next() {
testString += strconv.Itoa(e.Value.(int))
}
if testString != "123" {
t.Fatalf("removeDuplicates failed")
}
}

linked.go

package linked

import (
"container/list"
"strconv"
"strings"
)

func removeDuplicates(l *list.List) *list.List {
var newList = list.New()
var dupString string = ""
for e := l.Front(); e.Next() != nil; e = e.Next() {
if strings.Index(dupString, strconv.Itoa(e.Value.(int))) == -1 {
dupString += strconv.Itoa(e.Value.(int))
}
}
for _, c := range dupString {
newList.PushBack(c)
}
return newList
}

最佳答案

runeint32 的别名,

for _, c := range dupString {
newList.PushBack(c) // c is a rune aka int32
}

正在推送 int32,而 int 在 64 位 CPU 上别名为 int64,所以一种方法是强制输入:

for _, c := range dupString {
newList.PushBack(int(c))
}

关于list - 为什么将列表整数元素转换为字符串时得到 "interface conversion: interface is int32"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31498004/

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