Cannot move out of borrowed context: access struct field

struct Foo {
	bar: Option<String>
}

impl Foo {
	fn quuxify(&self) -> String {
		self.bar
			.map(|s| format!("Quux {}",s))
			.unwrap_or("Quux a tiger".to_string())
	}
}


main.rs:39:3: 39:7 error: cannot move out of borrowed content
main.rs:39 		self.bar

Generally I've gotten lifetimes and borrows, and such, but this one mystifies me, and I haven't been able to find documentation on how to address it besides cloning self.bar. I've tried, e.g., to take a reference to self.bar, call a function that takes a function to self.bar, etc.

I don't have a mental model for why rustc thinks I'm moving self in this case

Since Option::map takes ownership of the option, it would imply a move, in this case a move out of self. But since you don't want to modify the Option itself, you might want to use self.bar.as_ref().map(....) instead, to convert the Option<String> to an Option<&String> that leaves the original with ownership of the string.

4 Likes

Ah. So my mental model was deficient: the original struct owned (and the borrowed out) the contained String, not the Option itself. Thanks!