How to ref a struct

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

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=76e5204b317858cb0ccaf7c9056cac52

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

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!

wow 3Q