struct A { b: Option<B>, } struct B { name: String, } impl A { pub fn string(&self) -> String { let b = self.b.unwrap(); // ^^^^^^ cannot move out of borrowed content format!("{}", b.name) } } fn main() { let mut a = A { b: None }; if let None = a.b { a.b = Some(B { name: String::from("hello"), }) } println!("{}", a.string()); }
how to ref the struct b
Just change that one line:
let b = self.b.unwrap();
let b = self.b.as_ref().unwrap();
The data was moved into a -- thus, when you unwrap it, you end up moving it, unless you call as_ref first
a
as_ref
References can be thought of as "lightweight" versions of the data, because instead of holding the data, they refer to the location in memory where that data is stored. Much easier to pass around a 5lb dumbbell over a 100lbs of weight!
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.