2014-11-21 16 views
0

我有以下代碼段爲CRLF比較。它編譯和運行,但它似乎是一個奇怪的語法使用。我想知道是否有更自然的方式來進行比較而不是同時投射左右兩側。在鏽連接字節,字符串和比較

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; 
} 

回答

2

我會使用&'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],則不需要&。)

+0

謝謝。我從'BufferedStream :: read_line()'得到我的行,當我在別處讀取我的行時,我使用了&str :: read_line()'。 – Victory 2014-11-21 23:21:42