Skip to content

Instantly share code, notes, and snippets.

@marco-m
Created July 16, 2022 12:48
Show Gist options
  • Save marco-m/8d3d049c0ff6415d808a289cf2de0ec7 to your computer and use it in GitHub Desktop.
Save marco-m/8d3d049c0ff6415d808a289cf2de0ec7 to your computer and use it in GitHub Desktop.
Custom printing of Go structs with Stringer interface
package main
import (
"fmt"
"github.com/hashicorp/go-hclog"
)
type Cage struct {
Bo Bottle
Pa Pack
}
func (cage Cage) String() string {
return fmt.Sprintf("Bo:\n%v\nPa:\n%v\n", cage.Bo, cage.Pa)
}
type Bottle struct {
Volume int
Contents string
}
func (btl Bottle) String() string {
return fmt.Sprintf("Volume: %v\nContents: %v\n", btl.Volume, btl.Contents)
}
type Pack struct {
Material string
Liquid string
}
func (pac Pack) String() string {
return fmt.Sprintf("Material: %v\nLiquid: %v\n", pac.Material, pac.Liquid)
}
func main() {
log := hclog.New(&hclog.LoggerOptions{DisableTime: true})
cage := Cage{
Bo: Bottle{
Volume: 33,
Contents: "IPA",
},
Pa: Pack{
Material: "cardboard",
Liquid: "milk",
},
}
fmt.Println("1 Println")
fmt.Println(cage)
fmt.Printf("2 %%v\n%v\n", cage)
fmt.Printf("3 %%+v\n%+v\n", cage)
log.Info("parsed input together", "cage", cage)
log.Info("parsed input separated", "cage.Bottle", cage.Bo, "cage.Pack", cage.Pa)
}
// 1 Println
// Bo:
// Volume: 33
// Contents: IPA
//
// Pa:
// Material: cardboard
// Liquid: milk
//
//
// 2 %v
// Bo:
// Volume: 33
// Contents: IPA
//
// Pa:
// Material: cardboard
// Liquid: milk
//
//
// 3 %+v
// Bo:
// Volume: 33
// Contents: IPA
//
// Pa:
// Material: cardboard
// Liquid: milk
//
//
// [INFO] parsed input together:
// cage=
// | Bo:
// | Volume: 33
// | Contents: IPA
// |
// | Pa:
// | Material: cardboard
// | Liquid: milk
// |
//
// [INFO] parsed input separated:
// cage.Bottle=
// | Volume: 33
// | Contents: IPA
//
// cage.Pack=
// | Material: cardboard
// | Liquid: milk
@marco-m
Copy link
Author

marco-m commented Jul 16, 2022

Can be easily extended to redact sensitive fields.

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