Py学习  »  Redis

Golang Redis:地图和切片

Shashank Sachan • 4 年前 • 311 次点击  

我使用golang从redis散列获取数据,然后映射到结构中。

type Person struct {
    ID         string       `json:"id"`
    FirstName  string       `json:"firstName"`
    LastName   string       `json:"lastName"`
    Filters    interface{}  `json:"filters"`
    Type       string       `json:"type"`
}

在Redis中,哈希字段包含一个字符串化的JSON。

hget hashname字段名

上面返回一个字符串化的JSON。

现在“filters”键可以是基于类型的数组或映射(这就是为什么我将filters类型定义为struct中的接口)。
我将JSON整理如下:

var p Person
content, err := redis.HGet("hashName", "id").Result()
_ = json.Unmarshal([]byte(content), &p)

现在我必须循环使用下面这样的过滤器,但这会产生错误 不能超过p.筛选器(类型interface) (我知道为什么会出现这种错误)

for _, filter := range p.Filters {
  fmt.Println(filter)
}

我们有办法处理这种情况吗?

谢谢,
沙参

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/37895
 
311 次点击  
文章 [ 1 ]  |  最新文章 4 年前
poy
Reply   •   1 楼
poy    5 年前

你需要转换 Filters 类型 interface{} 到预期的切片中。如果你不知道它是什么类型,你可以用 map[string]interface{} . 因此改变你的 过滤器 类型到 映射[字符串]接口 .

更多信息 如果 过滤器 可以是一个数组(或者不是),那么您可以考虑 type switch :

一个简单的例子:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var i interface{}
    //json.Unmarshal([]byte(`["hi"]`), &i)
    json.Unmarshal([]byte(`{"a":"hi"}`), &i)

    switch i.(type) {
    case []interface{}:
        println("ARRAY")
    case map[string]interface{}:
        println("NOT ARRAY")
    default:
        fmt.Printf("%T\n", i)
    }
}