Writing Powers of 10 Compactly
In the Go Programming Language, Exercise 3.13 challenges programmers to write compact constant declarations for KB, MB, up to YB, representing powers of 1000. Despite the limitations of the iota mechanism for generating powers of 10, the text suggests using the most compact possible approach.
Floating-Point Literals
A space-efficient solution is to utilize floating-point literals with exponent parts. For instance, writing 1e3 takes up less space than 1000. Combining all identifiers into a single constant specification further reduces the number of equal signs. Here is a concise declaration (67 characters without spaces):
const ( KB, MB, GB, TB, PB, EB, ZB, YB = 1e3, 1e6, 1e9, 1e12, 1e15, 1e18, 1e21, 1e24 )
Integer Literals Using KB as Multiplier
Creating untyped integer constants requires writing 1000 for KB. To obtain subsequent values, the previous identifier can be multiplied by 1000. However, it is also possible to use KB as the multiplier, as it represents 1000. The following declaration is 77 characters without spaces:
const (KB,MB,GB,TB,PB,EB,ZB,YB = 1000,KB*KB,MB*KB,GB*KB,TB*GB,PB*KB,EB*KB,ZB*KB)
Using an Extra Const for Multiplication
Introducing an additional 1-character const x allows for further space savings by replacing *KB with x:
const (x,KB,MB,GB,TB,PB,EB,ZB,YB = 1000,x,x*x,MB*x,GB*x,TB*GB,PB*x,EB*x,ZB*x)
Rune Literal
Using a rune literal with a code point of 1000 ('Ϩ') reduces the space required by one more character:
const (x,KB,MB,GB,TB,PB,EB,ZB,YB = 'Ϩ',x,x*x,MB*x,GB*x,TB*GB,PB*x,EB*x,ZB*x)
The above is the detailed content of How Can I Compactly Declare Powers of 10 in Go?. For more information, please follow other related articles on the PHP Chinese website!