redis:无法封送map[string]string(实现encoding.BinaryMarshaler)----在Refis接口中

Bla*_*ght 1 go redis

我想创建一个通用的 Redis 接口来存储和获取值。我是 Golang 和 Redis 的初学者。如果需要对代码进行任何更改,我会请求您帮助我。

package main

import (
    "fmt"

    "github.com/go-redis/redis"
)

func main() {

    student := map[string]string{
        "id":   "st01",
        "name": "namme1",
    }

    set("key1", student, 0)
    get("key1")

}

func set(key string, value map[string]string, ttl int) bool {
    client := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "",
        DB:       0,
    })

    err := client.Set(key, value, 0).Err()
    if err != nil {
        fmt.Println(err)
        return false
    }
    return true
}

func get(key string) bool {
    client := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "",
        DB:       0,
    })

    val, err := client.Get(key).Result()
    if err != nil {
        fmt.Println(err)
        return false
    }
    fmt.Println(val)
    return true
}
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,我收到错误“redis:无法封送map[string]string(实现encoding.BinaryMarshaler)”。我尝试过使用 marshal 但没有用。我请求你帮我解决这个问题。

Lun*_*una 5

go的非标量类型无法直接转换为redis的存储结构,所以需要先转换结构再存储

如果要实现一个通用方法,那么该方法应该接收一个可以直接存储的类型,而调用者负责将复杂的结构转换为可用的类型,例如:

// ...

    student := map[string]string{
        "id":   "st01",
        "name": "namme1",
    }

    // Errors should be handled here
    bs, _ := json.Marshal(student)

    set("key1", bs, 0)

// ...

func set(key string, value interface{}, ttl int) bool {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

一个特定的方法可以构造一个特定的结构体,但是该结构体应该实现序列化器encoding.MarshalBinaryencoding.UnmarshalBinary,例如:

type Student map[string]string

func (s Student) MarshalBinary() ([]byte, error) {
    return json.Marshal(s)
}

// make sure the Student interface here accepts a pointer
func (s *Student) UnmarshalBinary(data []byte) error {
    return json.Unmarshal(data, s)
}

// ...

    student := Student{
        "id":   "st01",
        "name": "namme1",
    }

    set("key1", student, 0)

// ...

func set(key string, value Student, ttl int) bool {
    // ...
}
Run Code Online (Sandbox Code Playgroud)