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

查看:246
本文介绍了如何使用格式! 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.

如果您有分配器,则可以使用分配箱.此板条箱包含 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天全站免登陆