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

发布于 2025-01-02 16:46:41 字数 309 浏览 5 评论 0原文

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

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

是否有一种干净、实用的方法来连接数字和字符串?我想避免编写自己的串联或转换函数,但如果必须的话我会这样做。

I am trying to make a pure function that embeds a number in a string. The 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 string? I would like to avoid writing my own concatenation or conversion function, but I will if I have to.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁吢 2025-01-09 16:46:41

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

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


从OP编辑:我使用了像这样的函数将uints转换为字符串

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;
}

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

As far as I can tell, there are no matching pure functions in Phobos. I am afraid you are on your own.


Edit from the OP: I used a function like this one 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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文