How to define a petabyte constant in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

/*
   Go has two important features that make defining large constants easy:

   1. Untyped constants:
      These can grow arbitrarily large at compile time, so expressions like
      1 << 50 are perfectly safe and exact.

   2. Typed constants:
      When assigned to a type (e.g., uint64), Go checks that the value fits.

   A petabyte fits inside uint64:

       1 PiB = 2^50  = 1,125,899,906,842,624 bytes
       1 PB  = 10^15 = 1,000,000,000,000,000 bytes
*/

// Binary petabyte (pebibyte), using a bit shift.
// 1 << 50 = 2^50 bytes.
const PetabytePiB = 1 << 50

// Decimal petabyte (SI), using a readable numeric literal.
const PetabytePB = 1_000_000_000_000_000

func main() {
    fmt.Println("1 PiB =", PetabytePiB, "bytes")
    fmt.Println("1 PB  =", PetabytePB, "bytes")
}



/*
run:

1 PiB = 1125899906842624 bytes
1 PB  = 1000000000000000 bytes

*/

 



answered May 3 by avibootz
...