'How do I print a 2-Dimensional array as a grid in Golang?
The 2D Array I am trying to print as a board
Note: I am a complete novice at using Go and need this for a final project.
I am making an attempt to make the game, snake and ladders. I need to print a 10x10 2D array as a grid so it can look more like a board.
I've tried using:
for row := 0; row < 10; row ++ 10{
} for column := 0; column < 10; column++{
fmt.Println()
}
But it fails.
Any function or any method to do so?
Solution 1:[1]
You are almost there, you should pass the variable you want to print to fmt.Println
. Also keep in mind that this will always add a newline to the end of the output. You can use the fmt.Print
function to just print the variable.
for row := 0; row < 10; row++ {
for column := 0; column < 10; column++{
fmt.Print(board[row][column], " ")
}
fmt.Print("\n")
}
Bonus tip, instead of using hardcoded sizes you can also use range to loop over each element which works for arrays/slices of any size.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dylan Reimerink |