2016-08-04 2 views
0

다음 코드가 컴파일되지 않는 이유는 누구나 설명 할 수 있습니까?녹의 함수에 HashMap을 전달하는 방법

use std::collections::HashMap; 

fn add(mut h: &HashMap<&str, &str>) { 
    h.insert("foo", "bar"); 
} 

fn main() { 
    let mut h: HashMap<&str, &str> = HashMap::new(); 
    add(&h); 
    println!("{:?}", h.get("foo")); 
} 

이것은 rustc이 문제는 당신이 (즉, 참조가 다른 HashMap를 가리 키도록 변경 될 수 있습니다)는 HashMap에 변경 가능한 참조을 통과하지 것입니다

hashtest.rs:4:5: 4:6 error: cannot borrow immutable borrowed content `*h` as mutable 
hashtest.rs:4  h.insert("foo", "bar"); 
       ^

답변

1

나에게 말한다 무엇인가 a 변경 가능 참조 (HashMap) (즉, HashMap이 변경 될 수 있음).

use std::collections::HashMap; 

fn add(h: &mut HashMap<&str, &str>) { 
    h.insert("foo", "bar"); 
} 

fn main() { 
    let mut h: HashMap<&str, &str> = HashMap::new(); 
    add(&mut h); 
    println!("{:?}", h.get("foo")); 
} 
: 여기

는 올바른 코드입니다
관련 문제