Getting error interface conversion: interface {} is map[string]interface {}, not map[string]string – Why does it fail

huangapple go评论119阅读模式
英文:

Getting error interface conversion: interface {} is map[string]interface {}, not map[string]string - Why does it fail

问题

为什么以下语句失败:

// fileData 的类型为 PackageJson map[string]interface{}

dep, fDep := fileData["dependencies"]
if fDep {
    // 下面这行代码失败了
    version, fVer := dep.(map[string]string)[packageName]
}

上述语句抛出了一个错误:

interface conversion: interface {} is map[string]interface {}, not map[string]string [recovered]

在这里:

  • dep 的类型是 interface{}
  • 通过语句 dep.(map[string]string)[packageName],我没有告诉 dep 是一个键为字符串、值为字符串的映射吗?这意味着不同的吗?
英文:

Why does the following statement fail:

// type of fileData --> type PackageJson map[string]interface{}

dep, fDep := fileData["dependencies"]
if fDep {
    // Following Line Fails
    version, fVer := dep.(map[string]string)[packageName]
}

The above statement throws an error:

 interface conversion: interface {} is map[string]interface {}, not map[string]string [recovered]

Here:

  • dep is of type interface{}
  • With the statement dep.(map[string]string)[packageName], am I not telling that dep is a map with key as string and value as also the string? Does it mean different?

答案1

得分: 1

一个接口值包含两个部分:数据类型和该类型的数据值。像dep.(X)这样的类型断言会返回存储在接口dep中的值,如果该值的类型是X

所以,根据错误信息,你可以看到存储在dep中的值是map[string]interface{},而不是map[string]string。这就是为什么类型断言失败的原因。

根据代码,我认为你希望从该映射中获取一个字符串值。正如我之前所说,接口中包含一个值,所以一旦你恢复了dep中包含的值,你就可以访问一个键的值,该值也是一个interface{},然后再访问其中的值。所以:

k, ok := dep.(map[string]interface{})[packageName]
if ok {
   str, ok := k.(string)
   if ok {
      // k 是一个字符串,str 是映射中 `packageName` 键所包含的字符串
   } else {
      // k 不是一个字符串
   }
}
英文:

An interface value is two things: a data type, and a data value of that type. Type assertions like dep.(X) returns the value stored in the interface dep if that value is of type X.

So, based on the error, you can see that the value stored in dep is a map[string]interface{}, and not map[string]string. That's why type assertion fails.

Based on the code, I believe there is a tacit expectation that you want to get a string value from that map. As I said before, an interface contains a value in it, so once you recovered the value contained in dep, then you can access the value of a key, which is also an interface{}, and then access the value in that. So:

k,ok:=dep.(map[string]interface{})[packageName]
if ok {
   str, ok:=k.(string)
   if ok {
      // k is a string, and str is the string contained in `packageName` key in the map
   } else {
      // k is not a string
   }
}

huangapple
  • 本文由 发表于 2023年3月20日 00:16:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75783352.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定