Rabi Siddique
309 words
2 minutes
Truthiness in Golang
2024-02-13

In programming languages like Python and JavaScript, the concept of truthiness allows non-boolean values to be evaluated as either true or false in boolean contexts. This means that values other than the explicit boolean values True and False can be used in conditions.

Truthiness in Python#

In Python, values that evaluate to False in a boolean context are considered falsy, while all other values are considered truthy. Here are some examples:

Falsy values#

  • 0
  • None
  • False
  • Empty sequences (e.g., ”, [], {})

Truthy values#

  • Any non-zero number (e.g., 1, -1, 3.14)
  • Non-empty sequences (e.g., ‘hello’, [1, 2, 3], { ‘key’: ‘value’ })
  • Any other objects that are not explicitly falsy

Example#


num = 0
if num:
    print("This won't print because num is falsy")

num = 10
if num:
    print("This will print because num is truthy")

Truthiness in JavaScript#

In JavaScript, similar rules apply. Values such as 0, NaN, null, undefined, and '' (empty string) are considered falsy, while everything else is considered truthy.

Falsy values#

  • 0
  • NaN
  • null
  • undefined
  • false
  • ” (empty string)

Truthy values#

  • Any non-zero number (e.g., 1, -1, 3.14)
  • Non-empty strings (e.g., ‘hello’)
  • Objects (e.g., {}, [])
  • true

Example#

let num = 0;
if (num) {
  console.log("This won't print because num is falsy");
}

num = 10;
if (num) {
  console.log('This will print because num is truthy');
}

Truthiness in Go#

In Go, the concept of truthiness does not apply. The compiler requires boolean expressions to evaluate to explicit true or false. You cannot directly use non-boolean values in conditions without explicit comparison.

package main

import "fmt"

func main() {
    num := 0
    if num != 0 {
        fmt.Println("This won't print because num is 0 and the condition is false")
    }

    num = 10
    if num != 0 {
        fmt.Println("This will print because num is not 0 and the condition is true")
    }
}

In Go, you need to explicitly compare non-boolean values to determine their truthiness, as shown in the example. This explicitness makes the code clearer and avoids ambiguities that might arise from implicit truthiness.

Truthiness in Golang
https://rabisiddique.com/posts/truthiness-in-golang/
Author
Rabi Siddique
Published at
2024-02-13