无法在字符串映射内使用字符串的基础类型:“不能在映射索引中使用(类型)作为字符串类型”

问题描述:

This question already has an answer here:

I have underlying type of string: type Capability string.

I wanted to use it as a string inside map of strings but I am getting an error:

cannot use cap (type Capability) as type string in map index

This is my code:

package main

import (
    "fmt"
)


type Capability string
var caps_list = map[string]int {
    "HOME" : 1,
}

func main() {

    var cap Capability // string
    cap = "HOME"
    fmt.Print(string(caps_list[cap]))
}  

Why it doesn't accept it ? it is a string after all.

You can try my code here:
https://play.golang.org/p/r-h9Hu8_eoM

</div>

此问题已经存在 在这里有答案: p>

  • 在Go语言中将自定义类型转换为字符串 4个答案 li> ul> div>

    我有基本的字符串类型: type Capability string code >。 p>

    我想将其用作字符串映射中的一个字符串,但出现错误: p>

    不能使用大写字母( 类型能力)作为地图索引中的类型字符串 p> blockquote>

    这是我的代码: p>

     包main 
     \  nimport(
    “ fmt” 
    )
     
     
    type功能字符串
    var caps_list = map [string] int {
    “ HOME”:1,
    } 
     
    func main(){
     \  n var cap功能//字符串
     cap =“ HOME” 
     fmt.Print(string(caps_list [cap]))
    } 
      code>  pre> 
     
     

    为什么 不接受吗? 毕竟是一个字符串。 p>

    您可以在此处尝试我的代码:
    https://play.golang.org/p/r-h9Hu8_eoM p> div>

Just need to change to use string on the cap:

fmt.Print(string(caps_list[string(cap)]))  

No it is not a string. It is a type, wich base type is a string.

So the exact type is important. You can also not add celcius to fahrenheit degrees, even if both types would have integer base types.