Golang:将字节切片数组转换为整数数组

huangapple go评论75阅读模式
英文:

Golang : convert Byte slice array to integer array

问题

在Golang中,代码[body, err := ioutil.ReadAll(resp.Body)]中,ioutil.ReadAll()函数根据文档返回一个字节切片数组。

这个字节切片数组存储在变量body中。我的问题是如何将这个字节切片数组转换为整数数组。

英文:

In Golang, the code [body, err := ioutil.ReadAll(resp.Body)],
the ioutil.ReadAll()
returns a byte Slice array, based on the documentation.

This is stored in the variable 'body'. My question is how to convert this byte Slice array, to an array of Integers.

答案1

得分: 0

我刚刚找到了一些能实现我想要的功能的代码:

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)
}

所以这段代码确实实现了我想要的功能。

但是我对Golang感到失望,因为它没有一个简洁的一行代码可以完成这种类型的转换。
像这样的基本功能应该被封装起来,让程序员不必进行这种“低级”编程。

注意,我仍然喜欢Golang,他们在创建一种更好的C类型语言方面做了很多工作,相比C,它具有更高级的数据类型,并且使一些东西比C更具动态性。
只是对于这种经常出现的情况,他们没有为此提供高级抽象,让我感到失望。

英文:

I just found some code that does what I was wanting:

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)
}

So this code, does do what I want.

BUT l am disappointed in Golang, for not having a nice one liner that could do this
kind of conversion.
Certain basic things like this, should be packaged up for the programmer, and not have to do this kind of 'low' level programming.

Note, i still like Golang, they had done a lot to make a better C type language that has higher level Data Types when compared to C and also make some things more dynamic compared to C.
SO just disappointed they did not make a High Abstraction for this kind of case, which comes up quite a bit.

huangapple
  • 本文由 发表于 2021年8月31日 12:32:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/68992916.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定