Last active
February 17, 2022 05:26
-
-
Save olivere/a37f828d2018fb4a74cec400de4ba931 to your computer and use it in GitHub Desktop.
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 ( | |
"encoding/json" | |
"fmt" | |
"reflect" | |
) | |
type Article struct { | |
Title string `json:"title"` | |
Content string `json:"content"` | |
} | |
type Result struct { | |
Hits []string | |
} | |
func Example() { | |
const formatString = `{ | |
"title": %q, | |
"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"), | |
}, | |
} | |
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([]byte(hit), v.Addr().Interface()); err == nil { | |
slice = append(slice, v.Interface()) | |
} | |
} | |
return slice | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment