Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn a bool into an int? [duplicate]

Tags:

go

I'm used to C/Java, where I could use ?: as in:

func g(arg bool) int {
  return mybool ? 3 : 45;
}

Since Go does not have a ternary operator, how do I do that in go?

like image 251
jorgbrown Avatar asked Jul 18 '15 07:07

jorgbrown


1 Answers

You can use the following:

func g(mybool bool) int {
    if mybool {
        return 3
    } else {
        return 45
    }
}

And I generated a playground for you to test.

As pointed to by Atomic_alarm and the FAQ "There is no ternary form in Go."

As a more general answer to your question of "how to turn a bool into a int" programmers would generally expect true to be 1 and false to be 0, but go doesn't have a direct conversion between bool and int such that int(true) or int(false) will work.

You can create the trivial function in this case as they did in VP8:

func btou(b bool) uint8 {
        if b {
                return 1
        }
        return 0
}
like image 147
ssnobody Avatar answered Oct 13 '22 01:10

ssnobody