0
değişmez
use std::collections::HashMap;
struct Test1 {
total: u32,
hash: HashMap<u32, u32>,
}
impl Test1 {
fn new() -> Test1 {
Test1 {
total: 0,
hash: HashMap::new(),
}
}
fn add(&mut self) -> u32 {
self.total += 1;
self.total
}
fn get_or_create(&mut self, id: u32) -> u32 {
match self.hash.get(&id) {
Some(value) => *value,
None => {
let value = self.add();
self.hash.insert(id, value);
value
}
}
}
}
fn main() {
let mut test = Test1::new();
println!("{:?}", test.get_or_create(1));
println!("{:?}", test.get_or_create(1));
}
(çocuk kafesi) [http://is.gd/hDLEaL]
yapmaya çalışıyorum ama
<anon>:25:33: 25:37 error: cannot borrow `*self` as mutable because `self.hash` is also borrowed as immutable [E0502]
olsun ödünç çünkü
deneyin 'üzere maç self.hash.get (& id) .cloned() {' ve '* value'' içine { '' maçı self.hash.get (& id) değiştirmek için değer ' – qthree
Teşekkürler, çok mantıklı. İşe yarıyor!! – TlmaK0
Bunun nedeni, 'get'' seçeneğini <&u32> 'döndürür, ancak aslında bu ödünç referansa değil yalnızca değere ihtiyacınız vardır. Yani 'cloned(),' Seçenek <&T>' seçeneğini 'Seçenek''ya dönüştürür ve ödünç alır. –
qthree