我有以下用于比较 CR
和 LF
的代码片段。它编译并运行,但使用起来似乎是一种奇怪的语法。我想知道是否有更自然的方式来进行比较而无需同时转换左侧和右侧。
pub const CR: u8 = b'\r';
pub const LF: u8 = b'\n';
pub const CRLF: [u8, ..2] = [CR,LF]; // this probably should have a different type?
let mut cur_line: String;
// *snip getting line value*
// casting both the left and right hand side, is there a better way?
if cur_line.as_bytes() == &CRLF {
break;
}
最佳答案
我会使用 &'static [u8]
:
pub const CRLF: &'static [u8] = b"\r\n"; // or &[CR, LF]
我还要说的是,您应该小心使用的线型;是cur_line
保证是UTF-8?如果不是,应该是Vec<u8>
而不是 String
, 和 CRLF
可能应该是 &'static str
, "\r\n"
.不过反正比较cur_line.as_bytes() == CRLF
很好。 (一旦它是 &'static [u8]
而不是 [u8, ..2]
,则不需要 &
。)
关于rust - 在 Rust 中连接字节、字符串和比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27071836/