Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to pretty print byte array and char array?
    text
    copied!<p>In the following code, I'm trying to write a Txt() function to pretty print out my structure. It contains following minor questions in the full code:</p> <ol> <li>How to write one line to initialize Char array by string(line 47)</li> <li>How to speed up checking Char type without strings function(line 29,30)</li> <li>How to print out Char array as string(line 32)</li> <li>How to print out Char as string, maybe use Sprintf("%c"), but it is very slow.(line 34)</li> </ol> <p>full code at: <a href="http://play.golang.org/p/nUsg_qbufP" rel="nofollow">http://play.golang.org/p/nUsg_qbufP</a></p> <pre><code>type Char byte type THeader struct { Ver int8 // will show 1 Tag Char // will show 'H' } type TBody struct { B1 [3]byte // will show "[0,0,0]" B2 [4]Char // will show "ABCD" } func Txt(t interface{}) (s string) { val := reflect.ValueOf(t) typ := val.Type() fields := typ.NumField() for i := 0; i &lt; fields; i++ { sf := typ.Field(i) valfld := val.Field(i) vType := valfld.Type() s += sf.Name + ":" + vType.String() + ":" if strings.HasSuffix(vType.String(), "Char") { if strings.HasPrefix(vType.String(), "[") { v, ok := valfld.Interface().([4]Char) s += fmt.Sprint(ok, v) + "\n" } else { s += fmt.Sprint(valfld.Interface()) + "\n" } } else { s += fmt.Sprint(valfld.Interface()) + "\n" } } return } func main() { th := THeader{1, 'H'} fmt.Printf("%#v\n", th) // tb := TBody{B2: [10]Char("ABCD")} tb := TBody{B2: [4]Char{'A', 'B', 'C', 'D'}} fmt.Printf("%#v\n", tb) fmt.Print("Txt(th):\n", Txt(th), "\n") fmt.Print("Txt(tb):\n", Txt(tb), "\n") } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload