dongtuo3370
dongtuo3370
2018-10-10 12:07
浏览 150
已采纳

将空接口转换为Golang中的等效类型

Convert dynamic interface to its equivalent type. For example if value is int it should return int and if is string so it return int.

Code example:

var options = bson.M{}
for _, val := range conditions {
    var attr, operator, value interface{}
    cons := val.(map[interface{}]interface{})

    for range cons {
        attr     = cons["attribute"]
        operator = cons["operator"]
        value    = cons["value"]
        switch operator {
            case "==":
                operator = "$eq"
            case "!=":
                operator = "$ne"
            case "()":
                operator = "$in"
                value = []string{fmt.Sprintf("%v", value)}
        }
        options[attr.(string)] = bson.M{operator.(string): value. 
        (int)}
    }
}

Conditions come in below format.

conditions []interface{}
cons = append(cons, map[interface{}]interface{}{"attribute": 
"discontinued", "operator": "!=", "value": 1})

cons = append(cons, map[interface{}]interface{}{"attribute": "status", 
"operator": "==", "value": 1})

cons = append(cons, map[interface{}]interface{}{"attribute": 
"visibility", "operator": "==", "value": 4})

But the "value": 4 OR "value": 1 is not confirm.

Error thrown: interface conversion: interface {} is string, not int

图片转代码服务由CSDN问答提供 功能建议

将动态接口转换为其等效类型。 例如,如果value为int,则应返回int;如果为string,则应返回int。

代码示例:

  var options =  bson.M {} 
用于_,val:=范围条件{
 var attr,运算符,值接口{} 
缺点:= val。(map [interface {}] interface {})
 
用于范围 cons {
 attr = cons [“ attribute”] 
运算符= cons [“ operator”] 
 value = cons [“ value”] 
切换运算符{
 case“ ==”:
 operator =“  $ eq“ 
 case”!=“:
运算符=” $ ne“ 
 case”()“:
运算符=” $ in“ 
 value = [] string {fmt.Sprintf(”%v  “,value)} 
} 
 options [attr。(string)] = bson.M {operator。(string):value。  
(int)} 
} 
} 
   
 
 

条件以以下格式显示。

 条件 [] interface {} 
cons = append(cons,map [interface {}] interface {} {“ attribute”:
“ discontinued”,“ operator”:“!=”,“ value”:1})
  
cons = append(cons,map [interface {}] interface {} {“ attribute”:“ status”,
“ operator”:“ ==”,“ value”:1})
 
cons = append( 缺点,map [interface {}] interface {} {“ attribute”:
“ visibility”,“ operator”:“ ==”,“ value”:4})
   
  
 

但是“值”:4 “值”:1 不确定。

抛出错误: 接口转换:接口{}是字符串,而不是int

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doufan3958
    doufan3958 2018-10-10 12:20
    已采纳

    You can implement recursion to get the underlying value of interface using type assertions. Implement a Switch case and then call it recursively until you found the primitive type for unknown types. Since if you are parsing anything inside the interface it will surely be of below types.

    bool, for JSON booleans
    float64, for JSON numbers
    string, for JSON strings
    []interface{}, for JSON arrays // slice of interface{}
    map[string]interface{}, for JSON objects
    nil for JSON null
    

    Check for below code on how to implement the approach.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
         res, err := g.Execute( // Sends a query to Gremlin Server with bindings
               "g.V(x)",
                map[string]string{"x": "1234"},
                map[string]string{},
         )
         if err != nil {
              fmt.Println(err)
              return
         }
         fetchValue(res)
    }
    
    func fetchValue(value interface{}) {
        switch value.(type) {
        case string:
            fmt.Printf("%v is an interface 
     ", value)
        case bool:
            fmt.Printf("%v is bool 
     ", value)
        case float64:
            fmt.Printf("%v is float64 
     ", value)
        case []interface{}:
            fmt.Printf("%v is a slice of interface 
     ", value)
            for _, v := range value.([]interface{}) { // use type assertion to loop over []interface{}
                fetchValue(v)
            }
        case map[string]interface{}:
            fmt.Printf("%v is a map 
     ", value)
            for _, v := range value.(map[string]interface{}) { // use type assertion to loop over map[string]interface{}
                fetchValue(v)
            }
        default:
            fmt.Printf("%v is unknown 
     ", value)
        }
    }
    
    点赞 评论

相关推荐