2

wwww.985758.com13036075017at

 1 month ago
source link: https://studygolang.com/articles/36562
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

wwww.985758.com13036075017at

fyjcdfgxx · 7天之前 · 88 次点击 · · 大约8小时之前 开始浏览    

要把一个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:遍历赋值,不太优美:smile:

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

the end.


有疑问加站长微信联系(非本文作者))

280

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK