The blog post on error handling 
<https://blog.golang.org/error-handling-and-go> 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 
<https://golang.org/src/strings/strings.go?s=10915:10954#L416>:

    // Repeat returns 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
    }
    return string(b)
    }

Notice that when a negative value is supplied for the count argument, panic 
ensues <https://play.golang.org/p/v4Cd5C-Gdh> 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, returning 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.

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 
<https://golang.org/doc/go1compat> 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 return errors rather 
than panic, should strings.Repeat (and other such functions) always be 
implemented with more rigorous error handling? Or, should it always the 
caller's job to validate inputs that might cause a panic if otherwise 
unchecked?

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to