捕获数组索引错误

I'm just starting to learn Go, and I implemented an algorithm that checks four consecutive array indexes for an equal value in both diagonal directions, vertical, and horizontal. I designed it so that there is a function for each direction, and I'm wondering if there is a way for me to catch index errors without having to do the overhead to check if each index is in the range of index constraints.

func (state *State) checkTopLeftDiagonal(row, col int) bool {
    token := state.Board[row][col]
    b := token == state.Board[row-3][col-3] && token == state.Board[row-2][col-2] 
                  && token == state.Board[row-1][col-1]
    return b
}

func (state *State) CheckWinner(row, col int) bool {
    for i := 0; i < 4; i++ {
        if state.checkTopLeftDiagonal(row+i, col+i) == true {
            return true
        }
    }
    return false
}

What overhead?

"Heavy" and "slow" programs generally work with tens or hundreds of thousands of data points every second. A single if statement quite literally takes a handful of clock cycles out of the billions of clock cycles that your computer goes through every second (1 GHz = 1 billion clock cycles on a single core machine).

If you're worried about bounds checking overhead for (what seems to be) a fairly straightforward program, you shouldn't use Go. You shouldn't even use C++ or C. You should be writing this program directly in assembly and should spend hours fine-tuning each instruction to optimize on the scale of fractions of a nanosecond.

Like @leafbebop stated in the comments, any other pattern will carry significantly more overhead.


More generally, unless you go into a situation knowing the need for exceptionally high performance and low latency (such as electronic stock trading systems, gaming, or 3D rendering), it's usually better to build first and optimize later after you have "profiled" your code to identify the heavy parts. And unless your function is called millions of times a second, the amount of compute power that it'll use is virtually zero. What makes code slow is iterating over very large data sets, being bottlenecked waiting for the network (if processing thousands of network requests), or using large amounts of memory (in the range of gigabytes).

An if statement does not make a program slow.

Buying faster hardware is almost always cheaper than buying faster software (with more development time). :)