Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize error type in if-else

Tags:

In the code snippet below, how do I initialize an error variable?

err := nil                // can not compile, show "use of untyped nil" if xxx {     err = funcA() } else {     err = funcB() } if err != nil {     panic(err) } 

As you can see above, err will be used in the if-else blocks. I want to use one variable to get the result, but how do I initialize err here. Thanks!

like image 413
Jerry YY Rain Avatar asked Apr 21 '14 07:04

Jerry YY Rain


People also ask

What does it mean if variable is not initialised?

Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.

How do I return a custom error in go?

Within main() , we call doRequest() which returns an error interface to us. We first print the error message returned by the Error() method. Next, we attempt to expose all methods from RequestError by using the type assertion re, ok := err. (*RequestError) .

Which type of error is using variables that have not been initialized before use?

Should we declare a local variable without an initial value, we get an error. This error occurs only for local variables since Java automatically initializes the instance variables at compile time (it sets 0 for integers, false for boolean, etc.).


2 Answers

You can create a zero-valued error (which will be nil) by declaring the variable.

var err error if xxx {     err = funcA() } else {     err = funcB() } 

It's a common idiom, and you'll see it in plenty of code.

like image 191
Paul Hankin Avatar answered Sep 30 '22 18:09

Paul Hankin


This one looks a little hacky, but is valid too:

err := *new(error) 
like image 43
navigaid Avatar answered Sep 30 '22 17:09

navigaid