我想把字符串赋值给bytes数组:
var arr [20]byte
str := "abc"
for k, v := range []byte(str) {
arr[k] = byte(v)
}
还有别的方法吗?
我想把字符串赋值给bytes数组:
var arr [20]byte
str := "abc"
for k, v := range []byte(str) {
arr[k] = byte(v)
}
还有别的方法吗?
当前回答
我认为这样更好。
package main
import "fmt"
func main() {
str := "abc"
mySlice := []byte(str)
fmt.Printf("%v -> '%s'",mySlice,mySlice )
}
点击这里查看:http://play.golang.org/p/vpnAWHZZk7
其他回答
将字符串转换为字节片
您需要一种快速的方法将[]字符串转换为[]字节类型。用于将文本数据存储到随机访问文件或要求输入数据为[]字节类型的其他类型的数据操作等情况。
package main
func main() {
var s string
//...
b := []byte(s)
//...
}
这在使用ioutil时很有用。WriteFile,它接受字节片作为它的数据参数:
WriteFile func(filename string, data []byte, perm os.FileMode) error
另一个例子
package main
import (
"fmt"
"strings"
)
func main() {
stringSlice := []string{"hello", "world"}
stringByte := strings.Join(stringSlice, " ")
// Byte array value
fmt.Println([]byte(stringByte))
// Corresponding string value
fmt.Println(string([]byte(stringByte)))
}
输出:
你好,世界
请检查链接操场
小菜一碟:
arr := []byte("That's all folks!!")
string -> []byte用于将字符串转换为字节切片:
[]byte(str)
将数组转换为切片,使用[20]byte -> []byte:
arr[:]
将字符串复制到数组,使用string -> [20]byte:
copy(arr[:], str)
与上面相同,但首先显式地将字符串转换为slice:
copy(arr[:], []byte(str))
The built-in copy function only copies to a slice, from a slice. Arrays are "the underlying data", while slices are "a viewport into underlying data". Using [:] makes an array qualify as a slice. A string does not qualify as a slice that can be copied to, but it qualifies as a slice that can be copied from (strings are immutable). If the string is too long, copy will only copy the part of the string that fits (and multi-byte runes may then be copied only partly, which will corrupt the last rune of the resulting string).
这段代码:
var arr [20]byte
copy(arr[:], "abc")
fmt.Printf("array: %v (%T)\n", arr, arr)
...给出如下输出:
array: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ([20]uint8)
我还在围棋游乐场提供了它
除了上面提到的方法,你还可以做一个小技巧
s := "hello"
b := *(*[]byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))
Go Play: http://play.golang.org/p/xASsiSpQmC
你不应该使用这个:-)
如果有人正在寻找一个快速考虑使用不安全转换片之间,可以参考下面的比较。
package demo_test
import (
"testing"
"unsafe"
)
var testStr = "hello world"
var testBytes = []byte("hello world")
// Avoid copying the data.
func UnsafeStrToBytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(&s))
}
// Avoid copying the data.
func UnsafeBytesToStr(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
func Benchmark_UnsafeStrToBytes(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = UnsafeStrToBytes(testStr)
}
}
func Benchmark_SafeStrToBytes(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = []byte(testStr)
}
}
func Benchmark_UnSafeBytesToStr(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = UnsafeBytesToStr(testBytes)
}
}
func Benchmark_SafeBytesToStr(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = string(testBytes)
}
}
go test -v -bench="^Benchmark" -run=none
输出
cpu: Intel(R) Core(TM) i7-8565U CPU @ 1.80GHz
Benchmark_UnsafeStrToBytes
Benchmark_UnsafeStrToBytes-8 1000000000 0.2465 ns/op
Benchmark_SafeStrToBytes
Benchmark_SafeStrToBytes-8 289119562 4.181 ns/op
Benchmark_UnSafeBytesToStr
Benchmark_UnSafeBytesToStr-8 1000000000 0.2530 ns/op
Benchmark_SafeBytesToStr
Benchmark_SafeBytesToStr-8 342842938 3.623 ns/op
PASS