douzhi3454 2019-08-09 12:19
浏览 27

如何用字节数组作为字符串漂亮地打印结构?

I'm trying to decode dynamic structures from network data, here is simplified version. The FmtA is [3]byte, and required to print as string. So, here is my stupid implementation by defining a Bytes3 data type. If use this method, I should define Bytes6, Bytes4, Bytes2.

Is there any better method to print all byte arrays as strings instead of byte arrays?

package main                                                                                                                                                           

import "fmt"                                                                    

type Bytes3 [3]byte                                                             
type FmtA struct {                                                            
        Field1 Bytes3                                                           
        Field2 [6]byte                                                          
        Field3 uint8                                                            
}                                                                               
type FmtB struct {                                                            
        Field1 uint16                                                           
        Field2 [4]byte                                                          
        Field3 [2]byte                                                          
}                                                                               

func (b Bytes3) String() string {                                               
        v := [3]byte(b)                                                         
        return string(v[:])                                                     
}                                                                               
func main() {                                                                   
        a := FmtA{[3]byte{'a', 'b', 'c'}, [6]byte{'d', 'e', 'f', 'g', 'h', 'i'},
                36}                                                             
        b := FmtB{42, [4]byte{'a', 'b', 'c', 'd'}, [2]byte{'e', 'f'}}           
        var i interface{}   // simulate the received variable type                                                     
        i = a                                                                   
        fmt.Printf("a=%+v
", i)                                                
        i = b                                                                   
        fmt.Printf("b=%+v
", i)                                                
        // Output:                                                              
        // a={Field1:abc Field2:[100 101 102 103 104 105] Field3:36}            
        // b={Field1:42 Field2:[97 98 99 100] Field3:[101 102]}                 
}
  • 写回答

2条回答 默认 最新

  • dongzhao3040 2019-08-09 13:24
    关注

    You could create a utility function that would take any struct, inspect the fields using reflection and format them accordingly (use the default for fields that are not byte arrays, but force byte arrays to print as strings).

    Like for example:

    func Struct2String(theStruct interface{}) string {
        reflectV := reflect.ValueOf(theStruct)
        structType := reflectV.Type()
        b := &bytes.Buffer{}
        b.WriteString("{")
        for i := 0; i < reflectV.NumField(); i++ {
            if i > 0 {
                b.WriteString(" ")
            }
            b.WriteString(structType.Field(i).Name)
            b.WriteString(": ")
            fieldValue := reflectV.Field(i)
            fieldType := reflectV.Field(i).Type()
            fieldKind := reflectV.Field(i).Kind()
            if (fieldKind == reflect.Slice || fieldKind == reflect.Array) && fieldType.Elem().Kind() == reflect.Uint8 {
                fmt.Fprintf(b, "%s", fieldValue)
            } else {
                fmt.Fprint(b, fieldValue)
            }
        }
        b.WriteString("}")
        return b.String()
    }
    

    Here you can see the example running with the structs you have defined in a Go playground:

    https://play.golang.org/p/zGZM5S8UMWZ

    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败