如何在嵌入式平台中将 u32 数据转换为 &str?

Jam*_*med 4 embedded rust

我想在嵌入式 Rust 中将 u32 整数数据转换为字符串,但问题是在嵌入式中我们无法使用std代码,那么有什么方法可以做到这一点吗?

let mut dist = ((elapsed as f32 / mono_timer.frequency().0 as f32 * 1e6) / 2.0) / 29.1;
let dist = dist as u32;
let data = String::from("data:");
data.push_str(dist);
Run Code Online (Sandbox Code Playgroud)

Jam*_*med 5

找到答案

use core::fmt::Write;
use heapless::String;

fn foo() {
    let dist = 100u32;
    let mut data = String::<32>::new(); // 32 byte string buffer
    
    // `write` for `heapless::String` returns an error if the buffer is full,
    // but because the buffer here is 32 bytes large, the u32 will fit with a 
    // lot of space left. You can shorten the buffer if needed to save space.
    let _ = write!(data, "data:{dist}");
}
Run Code Online (Sandbox Code Playgroud)