为什么我不能使用整数作为地图键访问?

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

Why can't I access map key with an int?

问题

我创建了一个类似这样的地图:

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

我向其中添加了一些数字,使得数据格式如下:

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

然后我传入一个位置,例如"a1",在这里我遇到了问题。

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]
}

我得到了以下错误:'cannot use num (type int64) as type int in map index'

为什么会出现这个错误?如何访问地图中的键?

英文:

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?

答案1

得分: 5

你只需要将int64转换为int,像这样:

checkers.board[int(num)]

然而,如果你只是想从字符串中解析出一个整数,你应该使用strconv.Atoi。它会返回(int, error),所以你不需要进行转换。另外,请注意,你当前的代码写法对于两位数或两个字母前缀是无效的。这可能是有意为之的。

英文:

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.

答案2

得分: 3

使用以下代码:

num, err := strconv.Atoi(string(coordinates[1]))

该代码将返回一个 int 类型的值。

> strconv 包
>
> func Atoi
>
> func Atoi(s string) (i int, err error)
>
> AtoiParseInt(s, 10, 0) 的简写形式。

英文:

Use

num, err := strconv.Atoi(string(coordinates[1]))

which returns an int.

> Package strconv
>
> func Atoi
>
> func Atoi(s string) (i int, err error)
>
> Atoi is shorthand for ParseInt(s, 10, 0).

huangapple
  • 本文由 发表于 2014年7月22日 04:41:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/24874341.html
匿名

发表评论

匿名网友

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

确定