Can I functionally combine a number and a string?

I am trying to make a pure function that inserts a number into a string. Obvious concatenation methods do not work:

pure string foo(immutable int bar) { return "Number: " ~ bar; // Error: strings and ints are incompatible. return "Number: " ~ to!string(bar); // Error: to() is impure. } 

Is there a clean, functional way to concatenate a number and a string? I would like not to write my own concatenation or conversion function, but I will if I need to.

+6
source share
1 answer

This seems to be a long-standing problem !! (See this bugreport.)

As far as I can tell, there are no corresponding pure functions in Phobos. I am afraid that you yourself.


Edit from OP: I used such a function to convert uints to strings .

 import std.math: log10; pure string convert(uint number) { string result; while (log10(number) + 1 >= 1) { immutable uint lastDigit = number % 10; result = cast(char)('0' + lastDigit) ~ result; number /= 10; } return result; } 
+4
source

Source: https://habr.com/ru/post/907667/


All Articles