Bug 4119 – bigint string assign

Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2010-04-24T15:46:00Z
Last change time
2015-06-09T05:13:49Z
Assigned to
nobody
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2010-04-24T15:46:15Z
I'd like this code to work: import std.bigint: BigInt; void main() { BigInt i; i = "100_000_000_000_000_000_000_000_000_000"; } With dmd 2.043 it prints: test.d(4): Error: template bigint.BigInt.opAssign(T : long) does not match any function template declaration test.d(4): Error: template bigint.BigInt.opAssign(T : long) cannot deduce template function from argument types !()(string)
Comment #1 by clugdbug — 2010-04-24T19:40:20Z
That's a disgusting implicit cast. It doesn't belong in D (would be fine in a loosely-typed or scripting language). That should be rewritten as: BigInt i; i = BigInt("100_000_000_000_000_000_000_000_000_000"); Also, using magic numbers inside code is not something that should be encouraged.
Comment #2 by bearophile_hugs — 2010-04-25T04:41:54Z
Magic numbers are generally to avoid in serious code, it's often better to define some constants at the top of a function / struct/ class / module, and use them in the code. This also keeps all them equal if you have to use the same constant many times in the code. But multi-precision integers can be useful in little programs too (like 20-50 lines long), where the number literals are often acceptable. A good language must be able to "scale down" too. I agree that using a string literal is not very good, multi-precision integral literals are better, to be able to write a type-safe and clean-looking (or something similar): import std.bigint: BigInt; void main() { BigInt i; i = 100_000_000_000_000_000_000_000_000_000LL; } The usage of a string is a workaround, it's not very nice, but it's easy to implement, you just need to add this to BigInt (I have added it in my copy of the BigInt): void opAssign(T: string)(T x) { this = BigInt(x); } It's less safe than the multi-precision literal because the string can contain errors (spaces, etc), but this is true for the BigInt("...") syntax too. It's also a little less type-safe because the BigInt variable (here 'i') can be assigned with both an integral value and a string, so you can assign by mistake it to a unrelated string. But practice with dynamic languages shows that a bit of type flexibility doesn't burn down programs, it's not a Black Death. Especially in short programs. So I think until D gets multi-precision integral literals, the assign to string is acceptable.
Comment #3 by bearophile_hugs — 2013-11-18T02:30:56Z
Seems no one is interested in this, so I close this down.