Skip to content

Instantly share code, notes, and snippets.

@tetsuok
Created February 13, 2013 07:50
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tetsuok/4942960 to your computer and use it in GitHub Desktop.
Save tetsuok/4942960 to your computer and use it in GitHub Desktop.
Printing structs; convert structs to JSON format easily.
// Printing structs.
// http://research.swtch.com/gotour
package main
import (
"encoding/json"
"fmt"
"log"
)
type Arc struct {
Head string
Modifier string
}
func main() {
arc := Arc{"saw", "He"}
fmt.Printf("%v\n", arc)
fmt.Printf("%+v\n", arc)
fmt.Printf("%#v\n", arc)
// Convert structs to JSON.
data, err := json.Marshal(arc)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", data)
}
@solarfly73
Copy link

Yes, that's what I ended up doing. The error I made was that Marshal has 2 return values and I embedded the return into a function, which Bob says is bad habit and shouldn't be done in Go. Once I made the call return two variables (to separate err), then Println didn't print the byte array.

Thanks!!

@SerkanSipahi
Copy link

thanks works fine for me :)

@sarnobat
Copy link

sarnobat commented May 3, 2021

Works without any extra effort (for private fields too).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment