If the return variable has been defined in the return value list, do not use := in the if and declare this variable again.

Let’s look at this piece of business code:

 

 The main logic of the code is to find the community in the database based on the id value. The key is line 26. My original intention is that if db.Get does not get the community from the database and it is a sql.ErrNoRows error, then err will naturally be ErrorInvalidID, and naturally it will not be used. nil, since we declared err in the return value list, the returned err is also nil. If the upper layer calls this function and finds that err is not empty, it will naturally give the corresponding error logic, but the upper layer does not Doing that means that the err we return is not nil!

If you are careful, you must have noticed that the err on line 26 is green, that’s right! The error is on line 26!

Since we have already declared err in the return value list, and line 26 err := is equivalent to declaring another err temporary variable, so these two err are not one err! ! !

So the correct way is to change the := on line 26 to =

 

 

Guess you like

Origin blog.csdn.net/qq_55621259/article/details/128153952