我想把字符串赋值给bytes数组:

var arr [20]byte
str := "abc"
for k, v := range []byte(str) {
  arr[k] = byte(v)
}

还有别的方法吗?


当前回答

除了上面提到的方法,你还可以做一个小技巧

s := "hello"
b := *(*[]byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))

Go Play: http://play.golang.org/p/xASsiSpQmC

你不应该使用这个:-)

其他回答

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 main

import "fmt"

func main() {
    s := "abc"
    var a [20]byte
    copy(a[:], s)
    fmt.Println("s:", []byte(s), "a:", a)
}

输出:

s: [97 98 99] a: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

小菜一碟:

arr := []byte("That's all folks!!")

我认为这样更好。

package main

import "fmt"

func main() {
    str := "abc"
    mySlice := []byte(str)
    fmt.Printf("%v -> '%s'",mySlice,mySlice )
}

点击这里查看:http://play.golang.org/p/vpnAWHZZk7