[英]Rust struct field str slice with size
I can do the following:我可以执行以下操作:
#[repr(C, packed)]
#[derive(Clone, Copy, Debug)]
struct Test {
field: [u8; 8],
}
But I want to format it as a string when I'm using the debug formatter, and I'm wondering if I could define the field as a str slice with a known size.但是我想在使用调试格式化程序时将其格式化为字符串,并且我想知道是否可以将该字段定义为具有已知大小的 str 切片。 I can't use String because I am loading the struct from memory, where it is not instantiated by my Rust program.
我不能使用字符串,因为我从 memory 加载结构,我的 Rust 程序没有实例化它。 I have read that string slices are represented using UTF-8 characters, but I need ASCII.
我读过字符串切片是使用 UTF-8 字符表示的,但我需要 ASCII。 Should I manually implement the
Debug
trait instead?我应该手动实现
Debug
特征吗?
There's no automatic way of doing that, so you'll have to manually implement Debug
.没有自动的方法可以做到这一点,因此您必须手动实现
Debug
。 Be careful, however, that not every [u8; 8]
但是要小心,不是每个
[u8; 8]
[u8; 8]
is valid UTF-8 (unless you're actually guaranteed to get ASCII). [u8; 8]
是有效的 UTF-8 (除非你真的保证得到 ASCII)。
To be safe, you could switch whether to print field
as a string or as an array of bytes based on whether it's legal UTF-8:为了安全起见,您可以根据是否合法 UTF-8 来切换是将
field
打印为字符串还是字节数组:
use std::fmt;
impl fmt::Debug for Test {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let utf8;
let value: &dyn fmt::Debug = if let Ok(s) = std::str::from_utf8(&self.field) {
utf8 = s;
&utf8
} else {
&self.field
};
f.debug_struct("Test")
.field("field", value)
.finish()
}
}
fn main() {
let valid_ascii = Test {
field: [b'a'; 8],
};
let invalid_ascii = Test {
field: [0xFF; 8],
};
println!("{:?}", valid_ascii); // Test { field: "aaaaaaaa" }
println!("{:?}", invalid_ascii); // Test { field: [255, 255, 255, 255, 255, 255, 255, 255] }
}
If you're guaranteed valid ASCII, you can of course just use std::str::from_utf8_unchecked
and skip that step.如果您保证有效的 ASCII,您当然可以只使用
std::str::from_utf8_unchecked
并跳过该步骤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.