golang中赋值string到array

前端之家收集整理的这篇文章主要介绍了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 tot := 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

@H_404_131@byte f2 int } func main() { t := T1{f2: 3} copy(t.f1[:], "abcde") fmt. 方案2:遍历赋值,不太优美:)

@H_404_131@var
arr [20]byte str := "abc" for k, v := range []byte(str) { arr[k] = byte(v) } the end. 原文链接:https://www.f2er.com/go/191257.html

猜你在找的Go相关文章