Created
May 20, 2019 15:15
-
-
Save markbates/f8fa4b237dee5e52f7bdf8c5f8fc3982 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
"text/tabwriter" | |
) | |
type Beatle struct { | |
Name string | |
Instrument string | |
Quote string | |
} | |
func (b Beatle) String() string { | |
return fmt.Sprintf("%s plays %s", b.Name, b.Instrument) | |
} | |
func (b Beatle) GoString() string { | |
bb := &bytes.Buffer{} | |
bb.WriteString("Beatle{\n") | |
w := tabwriter.NewWriter(bb, 0, 0, 1, ' ', tabwriter.TabIndent) | |
fmt.Fprintf(bb, "\tName:\t\t%s\n", b.Name) | |
fmt.Fprintf(bb, "\tInstrument:\t%s\n", b.Instrument) | |
fmt.Fprintf(bb, "\tQuote:\t\t%s\n", b.Quote) | |
w.Flush() | |
bb.WriteString("}") | |
return bb.String() | |
} | |
func (b Beatle) Format(s fmt.State, verb rune) { | |
switch verb { | |
case 'v': | |
if s.Flag('#') { | |
fmt.Fprint(s, b.GoString()) | |
return | |
} | |
if s.Flag('+') { | |
m := map[string]Beatle{ | |
fmt.Sprintf("%T", b): b, | |
} | |
json.NewEncoder(s).Encode(m) | |
return | |
} | |
json.NewEncoder(s).Encode(b) | |
case 'q': | |
fmt.Fprintf(s, "%s said %s", b.Name, b.Quote) | |
default: | |
fmt.Fprint(s, b.String()) | |
} | |
} | |
func main() { | |
b := Beatle{ | |
Name: "John", | |
Instrument: "Guitar", | |
Quote: "Imagine all the people", | |
} | |
fmt.Printf("%#v\n", b) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment