我可以在功能上连接数字和字符串吗?

Max*_*xpm 6 functional-programming casting d concatenation phobos

我试图创建一个在字符串中嵌入数字的纯函数.明显的连接方法不起作用:

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

是否有一种干净,实用的方式来连接数字和字符串?我想避免编写自己的连接或转换函数,但如果必须,我会.

fnl*_*fnl 4

这似乎是一个长期存在的问题。(请参阅错误报告。)

据我所知,Phobos 中没有匹配的纯函数。恐怕你只能靠自己了。


从OP编辑:我使用了像这样的函数来转换uintsstrings.

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;
}
Run Code Online (Sandbox Code Playgroud)