Created
March 13, 2014 19:50
-
-
Save collinvandyck/9535592 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
| import ( | |
| "fmt" | |
| "reflect" | |
| "strings" | |
| ) | |
| type ToStringer struct { | |
| pieces []string | |
| } | |
| func (t *ToStringer) Add(name string, toAdd interface{}) *ToStringer { | |
| if toAdd == nil { | |
| return t | |
| } | |
| typ := reflect.TypeOf(toAdd) | |
| val := reflect.ValueOf(toAdd) | |
| if typ.Kind() == reflect.Ptr { | |
| if val.IsNil() { | |
| return t | |
| } | |
| // dereference the pointer | |
| toAdd = reflect.Indirect(val).Interface() | |
| } | |
| switch toAdd := toAdd.(type) { | |
| case string: | |
| if toAdd != "" { | |
| t.addPiece(fmt.Sprintf("%s=%q", name, toAdd)) | |
| } | |
| case int, int8, int32, int64, uint, uint8, uint16, uint32, uint64: | |
| t.addPiece(fmt.Sprintf("%s=%d", name, toAdd)) | |
| case float32, float64: | |
| t.addPiece(fmt.Sprintf("%s=%0.2f", name, toAdd)) | |
| default: | |
| t.addPiece(fmt.Sprintf("%s=%v", name, toAdd)) | |
| } | |
| return t | |
| } | |
| func (t *ToStringer) addPiece(piece string) { | |
| if piece != "" { | |
| t.pieces = append(t.pieces, piece) | |
| } | |
| } | |
| func (t *ToStringer) ToString() string { | |
| return "[" + strings.Join(t.pieces, " ") + "]" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment