Home>Article>Backend Development> How to start golang iota

How to start golang iota

(*-*)浩
(*-*)浩 Original
2019-12-03 11:01:13 3858browse

How to start golang iota

#iota is a constant counter in golang language and can only be used in constant expressions.

iota will be reset to 0 when the const keyword appears (before the first line inside const). Each new line of constant declaration in const will cause iota to count once(iota can be understood as the row index in the const statement block). (Recommended learning:go)

Using iota can simplify the definition and is very useful when defining enumerations.

In the constant definition, iota can conveniently iterate a value from 0 in steps of 1, 0,1,2,3,4,5...

This example is based on the 10th power carry of the file size format 2, shifting KB to the left by 10 bits, and MB to the left by 20 bits. . .

The Sprintf("%f",x) in this article will not cause an infinite loop bug because it is defined in the String method, because %f will not try to call String()

package main import ( "fmt" ) type ByteSize float64 const ( _ = iota KB ByteSize = 1 << (10*iota) MB GB TB PB EB ZB YB ) func (b ByteSize) String() string{ switch { case b >= YB: return fmt.Sprintf("%.2fYB",b/YB) case b >= ZB: return fmt.Sprintf("%.2fZB",b/ZB) case b >= EB: return fmt.Sprintf("%.2fEB",b/EB) case b >= PB: return fmt.Sprintf("%.2fPB",b/PB) case b >= TB: return fmt.Sprintf("%.2fTB",b/TB) case b >= GB: return fmt.Sprintf("%.2fGB",b/GB) case b >= MB: return fmt.Sprintf("%.2fMB",b/MB) case b >= KB: return fmt.Sprintf("%.2fKB",b/KB) } return fmt.Sprintf("%.2fB",b) } func main() { fmt.Println(ByteSize(1e10)) }

The above is the detailed content of How to start golang iota. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What are golang IDEs? Next article:What are golang IDEs?