如何将数组中的字符串转换为go中数组中的整数?

["1", "2", "3"]

[1, 2, 3]

I've searched for some solutions online but couldn't find it. I've tried 至 loop through the array and did strconv.ParseFloat(v, 64) where v is the value but it didn't work.

推荐答案

你必须在切片中循环.如果切片只包含整数,那么不需要ParseFloatAtoi就足够了.

import "fmt"
import "strconv"

func main() {
    var t = []string{"1", "2", "3"}
    var t2 = []int{}

    for _, i := range t {
        j, err := strconv.Atoi(i)
        if err != nil {
            panic(err)
        }
        t2 = append(t2, j)
    }
    fmt.Println(t2)
}

数到Playground.

Go相关问答推荐

如何预编译Golang标准库?

在Golang中Mergesort的递归/并行实现中出现死锁

Go SQLCMD比Windows本机版本慢吗?

go测试10m后如何避免超时

Json.Unmarshal() 和 gin.BindJson() 之间的区别

下载和合并时输出文件已损坏

同一文件上的多个 Arrow CSV 阅读器返回 null

Golang crypto/rand 线程安全吗?

使用 Grafana alert 在几分钟内重复alert

Go Colly 如何找到请求的元素?

如何将一片 map 转换为一片具有不同属性的 struct

如何在 Golang 中使用具有相同名称或特定关键字的行或列重新排列/排序 CSV

vs 代码调试 go 测试不通过标志

Go AST:获取所有 struct

如何正确为 Go 中的值设置多种类型?

跟踪长时间运行的任务的进度 - 正确的方法

将 Simple Go Web 应用程序部署到 Elastic Beanstalk

手动将 OpenTelemetry 上下文从 golang 提取到字符串中?

gob 解码器仅返回数组中的第一个元素

全局记录(across packages)