解决方事先注意:提问者首先声明输入切片是
 [] int8 
,这就是答案的意思。后来他意识到输入是
 [] uint8 
,它可以直接转换为
 string 
,因为
字节
 uint8 
的别名。



您不能转换不同类型的切片,您必须手动完成。



 [] byte  [] rune  [] byte 字符串 [] byte  [] rune 字符串


符文
是一个unicode代码点。如果我们尝试以一对一的方式将
 int8 
转换为
符文
,它将失败(意味着错误的输出),如果输入包含被编码为多个字节的字符(使用UTF-8),因为在这种情况下,多个
 int8 
值应该以一个<$ c $结尾c> rune 。

世界
  fmt.Println([] byte(世界))
//输出:[228 184 150 231 149 140]

其符号:

  fmt.Println([] rune(世界))
// [19990 30028]
 int8  rune  int8  byte 


 byte  uint8  0..255  [] int8  -128..127  -256 + bytevalue 世界 string  [] int8 
  [ -  28 -72 -106 -25 -107 -116] 
 bytevalue = 256 + int8value  int8  int8 字节 int  byte 
  if v< 0 {
b [i] = byte(256 + int(v))
} else {
b [i] = byte(v)
}
字节(v) 256 + v 
 []  append 

所以这里是最终转换:

  func B2S(bs [] int8)字符串{
b:= make([] byte,len(bs))
for i,v: =范围bs {
b [i] =字节(v)
}
返回字符串(b)
}

在<上尝试它a href =https://play.golang.org/p/pCymfKl_Hp =nofollow noreferrer> Go Playground 。


[]int8
[]bytestring(byteslice)[]int8
cannot convert ba (type []int8) to type string
baSliceScan()*sqlx.Rows[]int8string

Is this solution the fastest?

func B2S(bs []int8) string {
    ba := []byte{}
    for _, b := range bs {
        ba = append(ba, byte(b))
    }
    return string(ba)
}
uint8int8string(ba)
[]int8[]uint8stringbyteuint8

You can't convert slices of different types, you have to do it manually.

[]byte[]rune[]bytestring[]byte[]runestring
runeint8runeint8rune
"世界"
fmt.Println([]byte("世界"))
// Output: [228 184 150 231 149 140]

And its runes:

fmt.Println([]rune("世界"))
// [19990 30028]
int8runeint8byte
byteuint80..255[]int8-128..127-256+bytevalue"世界"string[]int8
[-28 -72 -106 -25 -107 -116]
bytevalue = 256 + int8valueint8int8byteintbyte
if v < 0 {
    b[i] = byte(256 + int(v))
} else {
    b[i] = byte(v)
}
byte(v)256 + v
[]append

So here is the final conversion:

func B2S(bs []int8) string {
    b := make([]byte, len(bs))
    for i, v := range bs {
        b[i] = byte(v)
    }
    return string(b)
}

Try it on the Go Playground.

这篇关于Golang将[] int8转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!