doujie7497 2011-11-08 01:33
浏览 27
已采纳

打印我的格式的有效方法

I wish there is an efficient way to print out my format. As I know convert to string may occur performance issue. Is there any better method?

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

The output is order_no=[65 48 48 48 49]qty=100 I wish it will be order_no=A0001 qty=100.

BTW, why func (t T)String() string work and func (t *T)String() string can not work.(on goplay)

  • 写回答

1条回答 默认 最新

  • dongzhong6675 2011-11-08 02:06
    关注
    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)
    }
    

    Output:

    order_no=A0001 qty=100
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥15 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)