bitSet := true
var bitSetVar int8
How can I assign bitSet
to bitSetVar
as 1
I can do this:
if bitSet {
bitSetVar = 1
} else {
bitSetVar = 0
}
Is this the best way?
bitSet := true
var bitSetVar int8
How can I assign bitSet
to bitSetVar
as 1
I can do this:
if bitSet {
bitSetVar = 1
} else {
bitSetVar = 0
}
Is this the best way?
Because the zero value for a int8
is 0
, the else branch is not necessary.
bitSet := true
var bitSetVar int8
if bitSet {
bitSetVar = 1
}
There are no conversions from bool
to integer types. The if statement is the best you can do.
yes this is the best way (fast and optimized):
bitSet := true
bitSetVar := int8(0)
if bitSet {
bitSetVar = 1
}
using var bitSetVar int8
or bitSetVar := int8(0)
inside a function is the same, and you don't need else
part, because the bitSetVar
initialized with zero before that if
statment.
while using if
is OK (and fast) like this B2i
function:
func B2i(b bool) int8 {
if b {
return 1
}
return 0
}
but you have another option using map
too (not as fast as if
, but nice and beautiful to show here):
var b2i = map[bool]int8{false: 0, true: 1}
like this working sample code (with commented outputs):
package main
import "fmt"
var b2i = map[bool]int8{false: 0, true: 1}
var i2b = []bool{false, true}
func B2i(b bool) int8 {
if b {
return 1
}
return 0
}
func main() {
fmt.Println(B2i(true)) // 1
fmt.Println(B2i(false)) // 0
fmt.Println(b2i[true]) // 1
fmt.Println(b2i[false]) // 0
fmt.Println(i2b[1]) // true
fmt.Println(i2b[0]) // false
}
Your way currently is the best, because it's fast, with the same way you can convert int8 to bool, even easier. Also you can save 1 line:
var bitSetVar int8
if bitSet {
bitSetVar = 1
}
Go community had an issue to implement this conversion, but seems that not all people are agree.
In terms of memory efficiency, going by your approach of doing
if bitSet {
bitSetVar = 1
} else {
bitSetVar = 0
}
you are not using any extra variables to set your bitSetVar
, hence I would say this is the best you could expect.
In terms of run-time, you are:
Checking the value of bitSet once, which is the least number of times you should be doing.
Setting the value of bitSetVar once, which you intend to do.
Till now, I would say you have been as efficient as you can be.
In terms of user readability, if you feel that this little snippet of code is making your code any less presentable, you could shift it into a function, maybe call it checkBitSetVar, like this:
func checkBitSetVar(mybool bool) int8{
if mybool{
return 1
}
return 0 //you just saved youself an else here!
}
and in the main, do:
setBitVar = checkBitSetVar(bitSet)
I think this is the best you can get out of Go.