Last active
          February 17, 2022 05:26 
        
      - 
      
- 
        Save olivere/a37f828d2018fb4a74cec400de4ba931 to your computer and use it in GitHub Desktop. 
Revisions
- 
        olivere revised this gist May 3, 2018 . 1 changed file with 7 additions and 7 deletions.There are no files selected for viewingThis 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 charactersOriginal file line number Diff line number Diff line change @@ -12,7 +12,7 @@ type Article struct { } type Result struct { Hits []string } func Example() { @@ -21,10 +21,10 @@ func Example() { "content": "%s article's content" }` var result = Result{ Hits: []string{ fmt.Sprintf(formatString, "First", "First"), fmt.Sprintf(formatString, "Second", "Second"), fmt.Sprintf(formatString, "Third", "Third"), }, } @@ -39,11 +39,11 @@ func Example() { // Title: Third, Content: Third article's content } func (r Result) Each(typ reflect.Type) []interface{} { var slice []interface{} for _, hit := range r.Hits { v := reflect.New(typ).Elem() if err := json.Unmarshal([]byte(hit), v.Addr().Interface()); err == nil { slice = append(slice, v.Interface()) } } 
- 
        olivere created this gist May 3, 2018 .There are no files selected for viewingThis 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,51 @@ package main import ( "encoding/json" "fmt" "reflect" ) type Article struct { Title string `json:"title"` Content string `json:"content"` } type Result struct { Hits [][]byte } func Example() { const formatString = `{ "title": %q, "content": "%s article's content" }` var result = Result{ Hits: [][]byte{ []byte(fmt.Sprintf(formatString, "First", "First")), []byte(fmt.Sprintf(formatString, "Second", "Second")), []byte(fmt.Sprintf(formatString, "Third", "Third")), }, } articlesContainer := result.Each(reflect.TypeOf(Article{})) for _, article := range articlesContainer { a := article.(Article) fmt.Printf("Title: %s, Content: %s\n", a.Title, a.Content) } // Output: // Title: First, Content: First article's content // Title: Second, Content: Second article's content // Title: Third, Content: Third article's content } func (r *Result) Each(typ reflect.Type) []interface{} { var slice []interface{} for _, hit := range r.Hits { v := reflect.New(typ).Elem() if err := json.Unmarshal(hit, v.Addr().Interface()); err == nil { slice = append(slice, v.Interface()) } } return slice }