donglu5041
2011-11-07 16:16
浏览 366
已采纳

在Go中将字符串转换为固定大小的字节数组

Is there convenient way for initial a byte array?

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

图片转代码服务由CSDN问答提供 功能建议

是否有方便的方法来初始化字节数组?

  包main 
import“ fmt” 
type T1 struct {
 f1 [5] byte //我在这里使用固定大小的文件格式或网络数据包格式。
 f2 int32 
} 
func main(){
t:  = T1 {“ abcde”,3} 
 // t:= T1 {[5] byte {'a','b','c','d','e'},3} //工作, 但是丑陋的
 fmt.Println(t)
} 
   
 
 

prog.go:8:不能将“ abcde”(类型字符串)用作类型[5] 如果将行更改为 t:= T1 {[5] byte(“ abcde”),3} \,则uint8为字段值

n

prog.go:8:无法将“ abcde”(类型字符串)转换为类型[5] uint8

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douruoshen1449 2011-11-08 04:21
    已采纳

    You could copy the string into a slice of the byte array:

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

    Edit: using named form of T1 literal, by jimt's suggestion.

    打赏 评论
  • douliang1900 2011-11-07 16:41

    Is there any particular reason you need a byte array? In Go you will be better off using a byte slice instead.

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

相关推荐 更多相似问题