Home > Software design >  Why is the .Bytes() value of a 0 big.Int an empty slice?
Why is the .Bytes() value of a 0 big.Int an empty slice?

Time:08-24

Why does calling .Bytes() on a zero value big.Int return a slice of length 0?

    // uint64
    var x uint64
    xb := make([]byte, 8)
    binary.BigEndian.PutUint64(xb, x)
    // [0 0 0 0 0 0 0 0]
    fmt.Println(xb)

    // uint8
    var y uint8
    yb := []byte{byte(y)}
    // [0]
    fmt.Println(yb)

    // big.Int
    z := big.Int{}
    zb := z.Bytes()
    // []               Why is this an empty slice and not [0]
    fmt.Println(zb)

CodePudding user response:

big.Int stores the absolute value of the number it represents in a slice. big.Int documents that "the zero value for an Int represents the value 0". So in the zero value (which represents 0) the slice will be empty (zero value for slices is nil and the length of a nil slice is 0).

The reasoning is simple: in cases where you don't use a big.Int value, it won't require allocation for the slice. Zero is the most special and probably the most frequent value, using this simple trick is a "no-brainer" optimization.

See related question: Is there another way of testing if a big.Int is 0?

  • Related