我该如何使用格式!no_std 环境中的宏? [英] How can I use the format! macro in a no_std environment?

查看:20
本文介绍了我该如何使用格式!no_std 环境中的宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用 std 的情况下实现以下示例?

How could I implement the following example without using std?

let text = format!("example {:.1} test {:x} words {}", num1, num2, num3);

text&strnum1num2num3 类型有任何数字类型.

text has type &str and num1, num2 and num3 have any numeric type.

我尝试使用 numtoaitoa/dtoa 来显示数字,但 numtoa 不支持浮点数和 itoa 不支持 no_std.我觉得在字符串中显示数字是相当普遍的,而且我可能遗漏了一些明显的东西.

I've tried using numtoa and itoa/dtoa for displaying numbers but numtoa does not support floats and itoa does not support no_std. I feel like displaying a number in a string is fairly common and that I'm probably missing something obvious.

推荐答案

一般来说,你.format! 分配一个 String,而 no_std 环境没有分配器.

In general, you don't. format! allocates a String, and a no_std environment doesn't have an allocator.

如果你有分配器,你可以使用 alloc crate.此 crate 包含 format! 宏.

If you do have an allocator, you can use the alloc crate. This crate contains the format! macro.

#![crate_type = "dylib"]
#![no_std]

#[macro_use]
extern crate alloc;

fn thing() {
    let text = format!("example {:.1} test {:x} words {}", 1, 2, 3);
}

另见:

这篇关于我该如何使用格式!no_std 环境中的宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆