how to convert bool to int8 in golang

47,482

Solution 1

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.

Solution 2

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
}

Solution 3

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.

Share:
47,482

Related videos on Youtube

Shahriar
Author by

Shahriar

I am an enthusiast professional with 6+ years of experience who love to take the challenges of acquiring knowledge. Skilled in Go, Kubernetes, Docker, ElasticSearch, Linux, Python. Strong engineering professional with a Bachelor of Science (B.Sc.) focused on Computer Science and Engineering. My objective is to improve my skills and expand my area of expertise.

Updated on July 21, 2022

Comments

  • Shahriar
    Shahriar almost 2 years
    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?

  • Admin
    Admin almost 4 years
    Good answer. I especially like your use of the words "checking" and "setting". There are no "conversions" from the bool type. See @MuffinTop.