chandu Ch
chandu Ch

Reputation: 43

if condition with multiple variable in golang

As I came from python background following go code is very confusing for me. can some one explain this?

if nferr, ok := err.(ops.NonFatalError); ok {
    w.NonFatalDiagnostics = w.NonFatalDiagnostics.Append(nferr.Diagnostics)
    return nil
}

Upvotes: 2

Views: 2556

Answers (1)

ssemilla
ssemilla

Reputation: 3970

This is called the "comma ok" idiom in Go which is essentially the same with:

nferr, ok := err.(ops.NonFatalError)
if ok {
    w.NonFatalDiagnostics = w.NonFatalDiagnostics.Append(nferr.Diagnostics)
    return nil
}

The only difference is the scope of nferr and ok which is within the if block.

how the variables nferr, ok would be evaluated?

If err is of type ops.NonFatalError, nferr will the concrete type of ops.NonFatalError, otherwise, ok will be false and nferr will be the zero value of ops.NonFatalError.

what is the variable ok before opening curly brace?

Look at the code above, it is essentially the same.

statement return nil, does it return from the function, the code is in?

Yes.

Edit

From @ThunderCat's comment which I highly suggest you go through, the Go tour explains a lot of syntax:

Type assertions

If with a short statement

Upvotes: 1

Related Questions