golang中赋值string到array

要把一个string赋值给一个array,哥哥遇到一个纠结的困难,研究一番,发现主要原因是array和slice在golang里不是一个东西,本文提供两种解决方案。


在网络编程中network packet transfer,经常要定义固定的字节长度,如下面的f1:

package main
import"fmt"
type T1 struct{
  f1 [5]byte// I use fixed size here for file format or network packet format.
  f2 int32
}
func main(){
  t := T1{"abcde",3}// t:= T1{[5]byte{'a','b','c','d','e'}, 3} // work, but ugly
  fmt.Println(t)}

prog.go:8: cannot use "abcde" (type string) as type [5]uint8 in field value

if I change the line to t := T1{[5]byte("abcde"), 3}

prog.go:8: cannot convert "abcde" (type string) to type [5]uint8

直接用copy(t.f1,"abcde")也是不行的。。因为copy的第一个参数必须是slice,


方案1:利用f1[:],注意,这里f1实际上是一个fixed的array,而f1[:]是一个slice

package main
import"fmt"
type T1 struct{
  f1 [5]byte
  f2 int}
func main(){
  t := T1{f2:3}
  copy(t.f1[:],"abcde")
  fmt.Println(t)}

方案2:遍历赋值,不太优美:)

 

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

the end.

原文地址:https://www.cnblogs.com/riskyer/p/3359915.html