gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:43:12 25 4
gpt4 key购买 nike

我正在开发一个 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"] 的类型使用以下类型断言开关 block :
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{}对象
  • []interface{}对于数组
  • string , bool , float64 , nil对于值

  • 所以当你得到一个 []interface{} ,它是一个数组,其元素可以是上述任何一种类型。您必须遍历每个并键入断言:
    switch v:=requestBody.Parameters[0]["users"].(type) {
    case []interface {}:
    for _,x:=range v {
    if s, ok:=x.(string); ok {
    // It is a string
    }
    }
    ...
    }

    关于go - 断言 []interface{} 类型的变量是否实际上是 []string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62782317/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com