Created
April 18, 2014 13:17
-
-
Save ewalk153/11043842 to your computer and use it in GitHub Desktop.
Demonstrate that the SetYAML method only works with pointer Fields
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 ( | |
| "fmt" | |
| "gopkg.in/yaml.v1" | |
| "time" | |
| ) | |
| type timeUnMarsh struct { | |
| time.Time | |
| } | |
| func (o *timeUnMarsh) SetYAML(tag string, value interface{}) (ok bool) { | |
| if t, ok := value.(string); ok { | |
| tx, err := time.Parse(time.RFC3339Nano, t) | |
| if err != nil { | |
| return true | |
| } | |
| o.Time = tx | |
| } | |
| return true | |
| } | |
| type WithPointer struct { | |
| St *timeUnMarsh | |
| } | |
| type NoPointer struct { | |
| St timeUnMarsh | |
| } | |
| // for debugging, just handle errors | |
| func errorc(err error) { | |
| if err != nil { | |
| panic(err) | |
| } | |
| } | |
| // demonstrate that SetYAML only works with Pointer fields | |
| func main() { | |
| in := []byte(`st: 2009-11-10T23:00:00Z`) | |
| withPointer := &WithPointer{} | |
| err := yaml.Unmarshal(in, withPointer) | |
| errorc(err) | |
| fmt.Println("withPointer:", withPointer) | |
| in2 := []byte(`st: 2010-11-10T23:00:00Z`) | |
| noPointer := &NoPointer{} | |
| err = yaml.Unmarshal(in2, noPointer) | |
| errorc(err) | |
| fmt.Println("noPointer:", noPointer) | |
| //Output: withPointer: &{2009-11-10 23:00:00 +0000 UTC} | |
| //noPointer: &{0001-01-01 00:00:00 +0000 UTC} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment