2016-09-20 54 views
0

的本来我写了这个:借款变化的类型为向量

fn split_line(line: &String) -> Vec<String> { 
    let mut chars = line.chars(); 
    let mut vec = Vec::new(); 
    let mut s = String::from(""); 
    while let Some(x) = chars.next() { 
     match x { 
      '<' => {}, 
      '/' => { 
         vec.push(s); 
         break; 
        } 
      ' ' => { 
         vec.push(s); 
         s.clear(); 
        } 
      _ => s.push(x), 
     } 
    } 
    vec 
} 

,并收到此错误: use of moved value: 's' 所以我改变vec.push(s)vec.push(&s),这打消了我原来的错误,但改变VEC从std::vec::Vec<std::string::String>std::vec::Vec<&std::string::String>

为什么?我如何在不改变vec的情况下借钱?

+0

Dosen't this make a vector of empty strings?只是改变数字? –

回答

2

当你做vec.push(s)时,s被移入向量中,这意味着s不再具有有意义的值。您所需要做的就是将s重置为新的String

fn split_line(line: &str) -> Vec<String> { 
    let mut chars = line.chars(); 
    let mut vec = Vec::new(); 
    let mut s = String::new(); 
    while let Some(x) = chars.next() { 
     match x { 
      '<' => {}, 
      '/' => { 
       vec.push(s); 
       break; 
      } 
      ' ' => { 
       vec.push(s); 
       s = String::new(); 
      } 
      _ => s.push(x), 
     } 
    } 
    vec 
} 
+1

那或'vec.push(s.clone())'。 –

+2

但是'String :: new()'不会马上分配。 :) –

+0

好点..... –