mardi 10 décembre 2019

golang `used as value` error when putting declaration on if (or switch) statement [duplicate]

I am trying the error.As in golang 1.13 to do error handling and encounter an interesting problem.

There is an example of using errors.As\Is in if... else if...:

if err == nil {
    // do nothing
} else if sqlerr := sqlite3.Error{}; errors.As(err, &sqlerr) && sqlerr.Code == sqlite3.ErrConstraint {
    // do something
}

But the compiler complains:

... se if sqlerr := sqlite3.Error{}; ...
                                 ^
syntax error: sqlerr := sqlite3.Error used as value

I guess the compiler treats { in sqlite3.Error{} as a part of if statement.

So why is this happening? And how to avoid it if I want to keep the declaration on if statement?

Aucun commentaire:

Enregistrer un commentaire