英文:
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)],
returns a byte Slice array, based on the documentation.
the ioutil.ReadAll()
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论