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

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

还有别的方法吗?


当前回答

例如,

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]

其他回答

例如,

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]

安全简单:

[]byte("Here is a string....")

我认为这样更好。

package main

import "fmt"

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

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

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)

我还在围棋游乐场提供了它

将字符串转换为字节片

您需要一种快速的方法将[]字符串转换为[]字节类型。用于将文本数据存储到随机访问文件或要求输入数据为[]字节类型的其他类型的数据操作等情况。

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

输出:

你好,世界

请检查链接操场