Monday, 8 March 2021

Calculate data size using Enum in Go

This method is learned from Youtube online course https://www.youtube.com/watch?v=YS4e4q9oBaU&t=5713s


I found it quite interesting and a nice demo to understand Enum in Go.

The code is like below:

package main

import (
"fmt"
)

const (
_ = iota //ignore first value by assigning to blank identifier
KB = 1 << (10 * iota)
MB
GB
TB
PB
ZB
YB
)

func main() {
fileSize := 4000000000.
fmt.Printf("%.2fGB", fileSize/GB)
}

Output:
3.73GB

Here constants KB, MB, GB, TB, PB, ZB and YB are used to calculate the responding size by dividing the constant value. Since they are written in upper case, which means they can be used in other packages as well. So it is a very useful tool.













No comments:

Post a Comment

Chapter 3 — The Molt

(This story is written by me and I will be posting it on Royal Road. Profile: https://www.royalroad.com/profile/1129550/fictions) Six fifty ...