I don't understand the evaluation rule here

Tony Lucas :

I am confused about a syntax usage in Go.

func f(){
    m := map[int]string{1: "one", 2: "two"}
    if x, ok := m[3]; !ok{
        // do something
    }
}

I understand what if x, ok := map[3] does, but I am confused about the difference between either have a ; !ok or a ; ok at the end, and the meaning of those two.

By the way, is it valid if I only write if x, ok := map[3] without a ; that extends it?

Thank you!

hobbs :

By the way, is it valid if I only write if x, ok := map[3] without a ; that extends it?

No, this is a syntax error, because x, ok := map[3] is not a boolean expression. In fact, it's not even an expression; a short variable declaration is a statement. So it can't be the expression that controls an if.

but I am confused about the difference between either have a ; !ok or a ; ok at the end, and the meaning of those two.

The same as for any if. If you want the block to run when ok is true, you use if ok. If you want the block to run when ok is false, you use if !ok. The only difference is that we've put the statement that gives ok its value between the word if and the test.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related