dpzbzp8728 2014-07-21 20:41
浏览 145
已采纳

为什么我不能使用int访问map键?

I create a map like so:

board := make(map[int]map[string]string)

I add some numbers to it so data is formatted like follows.

1 : map("a", "b" ..)

I then pass in a position. "a1" and this is where I hit a wall.

func (checkers *Checkers) setPiece(piece string, coordinates string) {
    lett := string(coordinates[0]);
    num, err := strconv.ParseInt(string(coordinates[1]), 0, 64)

    if err != nil {
        panic("Invalid coordinate format")
    }


    row := checkers.board[num]
}

I get the follow error: 'cannot use num (type int64) as type int in map index'

Why do I get this error? How do I access a key in the map?

  • 写回答

2条回答 默认 最新

  • dqwn64004 2014-07-21 20:53
    关注

    You just have to convert from int64 to int. like so:

    checkers.board[int(num)]
    

    However, if all you want is to parse an int out of a string, you should use strconv.AtoI for that. It will return (int, error) so you don't have to convert it. Also, keep in mind that the way your code is currently written will not work for 2-digit numbers or 2-letter prefixes. This may be by design.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)