打印我的格式的有效方法

时间:2011-11-08 01:33:21

标签: go

我希望有一种有效的方式来打印我的格式。 据我所知转换为字符串可能会出现性能问题。 有没有更好的方法?

package main

import "fmt"

type T struct {
  order_no [5]byte
  qty int32
}
func (t T)String() string {
  return fmt.Sprint("order_no=", t.order_no, 
    "qty=", t.qty)
}

func main() {
        v := T{[5]byte{'A','0','0','0','1'}, 100}

    fmt.Println(v)
}    

输出为order_no=[65 48 48 48 49]qty=100 我希望它是order_no=A0001 qty=100

BTW,为什么func (t T)String() string工作而func (t *T)String() string无效。(在goplay上)

1 个答案:

答案 0 :(得分:1)

package main

import "fmt"

type T struct {
    order_no [5]byte
    qty      int32
}

func (t T) String() string {
    return fmt.Sprint(
        "order_no=", string(t.order_no[:]),
        " qty=", t.qty,
    )
}

func main() {
    v := T{[5]byte{'A', '0', '0', '0', '1'}, 100}
    fmt.Println(v)
}

输出:

order_no=A0001 qty=100
相关问题