How can I get the string representation of a struct?

前端 未结 5 807
闹比i
闹比i 2021-01-30 16:04

For my application, it does not matter if the string is human readable or not.

5条回答
  •  时光说笑
    2021-01-30 16:11

    If it's a "one way" serialization (for debugging or logging or whatever) then fmt.Printf("%#v", var) is very nice. (Update: to put the output into a string instead of printing it, use str := fmt.Sprintf("%#v", var).

    If size matters you can use %v, but I like %#v because it will also include the field names and the name of the struct type.

    A third variation is %+v which will include the field names, but not the struct type.

    They are all documented at the top of the fmt documentation.

    If you need two-way serialization JSON, Gob or XML are the easiest/built-in options in Go, see the encoding packages.

提交回复
热议问题