如何使用格式! no_std环境中的宏? [英] How can I use the format! macro in a no_std environment?
问题描述
如何在不使用std的情况下实现以下示例?
How could I implement the following example without using std?
let text = format!("example {:.1} test {:x} words {}", num1, num2, num3);
text
具有类型&str
和num1
,num2
和num3
具有任何数字类型.
text
has type &str
and num1
, num2
and num3
have any numeric type.
我尝试使用numtoa
和itoa/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.
如果您有分配器,则可以使用分配箱.此板条箱包含 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屋!