-
Notifications
You must be signed in to change notification settings - Fork 17.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: Go2: must(): Improve code density for handling rare fatal errors #21419
Comments
What prevents you from writing this function in your code? |
See also #20803 (comment). |
Because, we can not write this function only with golang compiler. How to define that |
Wouldn't it be possible to write a |
@tmthrgd |
@bronze1man You could create a func must<T>(arg T, err error) T {
if err != nil {
panic(err)
}
return arg
}
func must<T0, T1>(arg0 T0, arg1 T1, err error) (T0, T1) {
if err != nil {
panic(err)
}
return arg0, arg1
}
func must<T0, T1, T2>(arg0 T0, arg1 T1, arg2 T2, err error) (T0, T1, T2) {
if err != nil {
panic(err)
}
return arg0, arg1, arg2
}
// ... and so on ... numberString := "0" // string that we know contains only digits
fmt.Printf("Your number times two is %d\n", 2*must(strconv.Atoi(numberString))) |
@tmthrgd I think I can write a function that can do compute at compile time, and output the right code base on input type, should be better solution to this kind of problem. |
What do you mean by that and how it relates to this proposal? |
Instead of this:
I would like to write this:
The semantics of must() are: evaluate the single expression inside, which returns N values (N>=1); if the Nth value is non-nil, pass the Nth value to panic(); otherwise, return the first N-1 values.
must() is especially useful in unit tests, where I find a 25% of my code is error handling for errors that should really never happen, and if they did, panic() is fine.
must() is a built-in function like "append"; it can be re-declared in user code. Thus, introducing this function would not create backward compatibility issues.
must() is inspired by regexp.MustCompile.
Thanks,
-Ken
Kenneth Duda
The text was updated successfully, but these errors were encountered: