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?
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.
Use
num, err := strconv.Atoi(string(coordinates[1]))
which returns an int
.
func Atoi(s string) (i int, err error)
Atoi
is shorthand forParseInt(s, 10, 0)
.