繁体   English   中英

断言 []interface{} 类型的变量是否实际上是 []string

[英]Assert if variable of type []interface{} is actually []string

我正在开发一个 RESTful API,需要确定用户发送了什么。

假设这是 JSON 格式的 POST 请求的主体:

{
    "request": "reset-users",
    "parameters": [
        {
            "users": ["userA","userB","userC"]
        }
    ]
}

使用json.Unmarshal ,我将正文读入这个标准化结构:

type RequestBody struct {
    Request string `json:"request"`
    Parameters []map[string]interface{} `json:"parameters"`
}

所以,现在,我可以使用以下类型断言开关块检查requestBody.Parameters[0]["users"]的类型:

switch requestBody.Parameters[0]["users"].(type) {
    case []interface {}:
        //It is actually a list of some type
    default:
        //Other types
}

上面提到的代码有效,但我如何才能确定某种类型的列表是字符串列表? (相对于 int 或 bool 的列表...)

解组到interface{}时,标准库解组器始终使用以下内容:

  • 对象的map[string]interface{}
  • arrays 的[]interface{}
  • string , bool , float64 , nil的值

因此,当您获得[]interface{}时,它是一个数组,其元素可以是上述任何一种类型。 您必须通过每个 go 并键入断言:

switch v:=requestBody.Parameters[0]["users"].(type) {
    case []interface {}:
      for _,x:=range v {
         if s, ok:=x.(string); ok {
            // It is a string
         }
      }
   ...
}

文档清楚地说明了它将使用什么类型:“[]interface{},用于 JSON 数组”。 它始终是[]interface{} ,这是一个具体类型,不能断言为任何其他类型; 它不能是[]string ,因为这是与[]interface{}不同的类型。 []interface{}的每个元素都可以是文档中列出的任何类型,具体取决于原始 JSON 数组的每个元素的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM