Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the string representation of a struct?

Tags:

string

struct

go

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

like image 669
abw333 Avatar asked May 02 '13 05:05

abw333


People also ask

Can a struct contain a string?

Short answer: keep in mind that strings are immutable types. Create your struct normally, and realize that the struct only contains a reference to the string, not a magically resizing segment of the struct that expands to include your volatile string.

How do I convert a struct to a string in hive?

if your intention is to get value out of struct and store it as a primitive value then try like below, create external table table2 ( a string, b_c string, b_d string, c string ) insert overwrite table table2 select a,b.c,b.e,c from table1; Let me know if this helps.

What is an idiomatic way to customize the representation of a custom struct in a formatted string?

What is an idiomatic way to customize the representation of a custom struct in a formatted string? There is no customizing the string representation of a type. Build it in pieces each time by calling individual fields. Create a wrapper function that accepts your type and outputs a string.


1 Answers

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.

like image 95
Ask Bjørn Hansen Avatar answered Sep 18 '22 18:09

Ask Bjørn Hansen