Created
July 16, 2022 12:48
-
-
Save marco-m/8d3d049c0ff6415d808a289cf2de0ec7 to your computer and use it in GitHub Desktop.
Custom printing of Go structs with Stringer interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can be easily extended to redact sensitive fields.