Skip to content

Commit e113512

Browse files
committed
Add example showing scanning to struct
1 parent f9dfc7a commit e113512

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

example_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,40 @@ func ExampleClient_ScanType() {
276276
// Output: found 33 keys
277277
}
278278

279+
// ExampleStringStringMapCmd_Scan shows how to scan the results of a map fetch
280+
// into a struct.
281+
func ExampleStringStringMapCmd_Scan() {
282+
rdb.FlushDB(ctx)
283+
err := rdb.HMSet(ctx, "map",
284+
"name", "hello",
285+
"count", 123,
286+
"correct", true).Err()
287+
if err != nil {
288+
panic(err)
289+
}
290+
291+
// Get the map. The same approach works for HmGet().
292+
res := rdb.HGetAll(ctx, "map")
293+
if res.Err() != nil {
294+
panic(err)
295+
}
296+
297+
type data struct {
298+
Name string `redis:"name"`
299+
Count int `redis:"count"`
300+
Correct bool `redis:"correct"`
301+
}
302+
303+
// Scan the results into the struct.
304+
var d data
305+
if err := res.Scan(&d); err != nil {
306+
panic(err)
307+
}
308+
309+
fmt.Println(d)
310+
// Output: {hello 123 true}
311+
}
312+
279313
func ExampleClient_Pipelined() {
280314
var incr *redis.IntCmd
281315
_, err := rdb.Pipelined(ctx, func(pipe redis.Pipeliner) error {

0 commit comments

Comments
 (0)