خرید بک لینک

Vote count: 0

The blog post on error handling in go establishes the following guideline:

In Go, error handling is important. The language's design and conventions encourage you to explicitly check for errors where they occur (as distinct from the convention in other languages of throwing exceptions and sometimes catching them).

Here's the implementation of strings.Repeat:

// Repeat retus a new string consisting of count copies of the string s.
func Repeat(s string, count int) string {
    b := make([]byte, len(s)*count)
    bp := copy(b, s)
    for bp < len(b) {
        copy(b[bp:], b[:bp])
        bp *= 2
    }
    retu string(b)
}

Notice that when a negative value is supplied for the count argument, panic ensues because it attempts to make a byte slice of negative length:

package main

import "strings"

func main() {
    strings.Repeat("panic!", -1)
}

Output:

panic: runtime error: makeslice: len out of range

Of course, retuing two values from strings.Repeat would make it less convenient to use, but it does reflect what can happen if the value calculated for the count argument is negative for whatever reason (probably a bug!).

Another option would have been to use a uint for the count argument but that would introduce a different kind of inconvenience for both the caller and the implementation.

I am fully aware of the go compatibility promise and I'm not proposing a change to strings.Repeat. I can code a custom Repeat function for my own purposes. The purpose of the question is to better understand error handling in go.

So, considering the recommendation from the go blog to retu errors rather than panic, should strings.Repeat (and other such functions) be implemented with more rigorous error handling? Or, should it always the caller's job to validate inputs?

asked 43 secs ago

برچسب: نویسنده: استخدام کار تاريخ: پنجشنبه 10 تير 1395 ساعت: 23:16

صفحه بندی