mirror of
https://github.com/redis/go-redis.git
synced 2025-06-14 01:21:30 +03:00
Add scan struct example (#1870)
This commit is contained in:
committed by
GitHub
parent
989295a24b
commit
ed42d3c37b
50
example/scan-struct/main.go
Normal file
50
example/scan-struct/main.go
Normal file
@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
"github.com/go-redis/redis/v8"
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Str1 string `redis:"str1"`
|
||||
Str2 string `redis:"str2"`
|
||||
Int int `redis:"int"`
|
||||
Bool bool `redis:"bool"`
|
||||
Ignored struct{} `redis:"-"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
ctx := context.Background()
|
||||
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: ":6379",
|
||||
})
|
||||
|
||||
// Set some fields.
|
||||
if _, err := rdb.Pipelined(ctx, func(rdb redis.Pipeliner) error {
|
||||
rdb.HSet(ctx, "key", "str1", "hello")
|
||||
rdb.HSet(ctx, "key", "str2", "world")
|
||||
rdb.HSet(ctx, "key", "int", 123)
|
||||
rdb.HSet(ctx, "key", "bool", 1)
|
||||
return nil
|
||||
}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
var model1, model2 Model
|
||||
|
||||
// Scan all fields into the model.
|
||||
if err := rdb.HGetAll(ctx, "key").Scan(&model1); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Or scan a subset of the fields.
|
||||
if err := rdb.HMGet(ctx, "key", "str1", "int").Scan(&model2); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
spew.Dump(model1)
|
||||
spew.Dump(model2)
|
||||
}
|
Reference in New Issue
Block a user