0

Its not clear why a borrowed reference is not able to make a call to the function.

Standard Error

   Compiling playground v0.0.1 (/playground)
warning: unused variable: `a`
  --> src/main.rs:23:9
   |
23 |     let a = Astruct::new(Atype::TypeA, 100);
   |         ^ help: consider prefixing with an underscore: `_a`
   |
   = note: #[warn(unused_variables)] on by default

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:13:14
   |
13 |         Some(self.aType)
   |              ^^^^^^^^^^ cannot move out of borrowed content

error: aborting due to previous error

For more information about this error, try `rustc --explain E0507`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.
enum Atype {
    TypeA,
    TypeB,
}

struct Astruct {
    pub aType : Atype,
    pub aVal : i32,
}

impl Astruct {
    pub fn getType(&self) -> Option<Atype> {
        Some(self.aType)
    }

    pub fn new(aType: Atype, aVal: i32) -> Astruct {
       Astruct { aType: aType,
                 aVal: aVal}
    }
}

fn main() {
    let a = Astruct::new(Atype::TypeA, 100);

    //println!("Type: {} Val: {}", a.aType, a.aVal);
}
max taldykin
  • 12,459
  • 5
  • 45
  • 64
  • 2
    Because you are making a move operation in the function, you can't move anything from a borrowed content. It would be something like moving gpu to your computer from some else's computer which is borrowed*. [Copying/Cloning](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c957e1d912ad36678997dc54085d1811) would work but i suggest you to understand the concept and costs first – Ömer Erden Jul 04 '19 at 19:48
  • It's not clear why you wouldn't just let callers borrow the value - [Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=93287a443e29e742e8c92fe06a2fbf44) – Mark Jul 04 '19 at 20:12
  • Thanks for the input. – Nilanjan Goswami Jul 04 '19 at 20:14
  • Can you provide some link explaining these concepts with examples? – Nilanjan Goswami Jul 04 '19 at 20:21
  • 3
    [The Rust Book](https://doc.rust-lang.org/book/) maybe? – Mark Jul 04 '19 at 20:24

1 Answers1

0

You are trying to move aType out of the struct Astruct and return it from the method getType. However, getType only borrows Astruct (as you can see from &self). Since getType doesn't own Astruct, it can't move anything out of it.

Depending on what you are trying to do, you have some options:

  1. Make Atype derive Copy and Clone, such that it can copy aType. To me this seems like what you wanted to do:
#[derive(Copy, Clone)]
enum Atype {
    TypeA,
    TypeB,
}
  1. Make getType consume Astruct:
pub fn getType(self) -> Option<Atype> {
  Some(self.aType)
}
  1. Make getType return a reference to Atype
pub fn getType(&self) -> Option<&Atype> {
  Some(&self.aType)
}

Each of these options has its pros and cons.

Emoun
  • 2,297
  • 1
  • 13
  • 20