if condition with multiple variable in golang

1475 views go
4

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
}
  • how the variables nferr, ok would be evaluated?
  • what is the variable ok before opening curly brace?

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

answered question

1 Answer

0

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

posted this

Have an answer?

JD

Please login first before posting an answer.