I have a file called info.rs that contains a small test structure intended to represent some basic file information. The code below is learning code for using structs:
pub struct FileInfo {
name: String,
path: String,
}
impl FileInfo {
pub fn new(aname: String,apath: String) {
FileInfo {
name: aname,
path: apath
}
}
pub fn get_name(&self) {
self.name
}
pub fn get_path(&self) -> String {
self.path
}
}
According to documentation (and several examples!), the &self parameter used in the above functions refers to the calling structure, in this case the FileInfo struct. The intent is to allow my main.rs code to get access to the name and path:
mod info;
use info::FileInfo;
fn main() {
println!("Listing files in current directory.");
let fdat = FileInfo::new(String::from("File.txt".),String::from("./File.txt"));
println!("Name: {}",fdat.get_name());
println!("Path: {}",fdat.get_path());
}
Unfortunately, compilation fails with the following messages:
error[E0507]: cannot move out of borrowed content
--> src\info.rs:79:9
|
79 | self.name
| ^^^^^^^^^ cannot move out of borrowed content
error[E0507]: cannot move out of borrowed content
--> src\info.rs:83:9
|
83 | self.path
| ^^^^^^^^^ cannot move out of borrowed content
error: aborting due to 2 previous errors
This makes no sense, because code from https://doc.rust-lang.org/rust-by-example/fn/methods.html accesses the &self parameters in the same way that I am:
struct Point {
x: f64,
y: f64,
}
// Implementation block, all `Point` methods go in here
impl Point {
// This is a static method
// Static methods don't need to be called by an instance
// These methods are generally used as constructors
fn origin() -> Point {
Point { x: 0.0, y: 0.0 }
}
// Another static method, taking two arguments:
fn new(x: f64, y: f64) -> Point {
Point { x: x, y: y }
}
}
struct Rectangle {
p1: Point,
p2: Point,
}
impl Rectangle {
// This is an instance method
// `&self` is sugar for `self: &Self`, where `Self` is the type of the
// caller object. In this case `Self` = `Rectangle`
fn area(&self) -> f64 {
// `self` gives access to the struct fields via the dot operator
let Point { x: x1, y: y1 } = self.p1;
let Point { x: x2, y: y2 } = self.p2;
// `abs` is a `f64` method that returns the absolute value of the
// caller
((x1 - x2) * (y1 - y2)).abs()
}
fn perimeter(&self) -> f64 {
let Point { x: x1, y: y1 } = self.p1;
let Point { x: x2, y: y2 } = self.p2;
2.0 * ((x1 - x2).abs() + (y1 - y2).abs())
}
// This method requires the caller object to be mutable
// `&mut self` desugars to `self: &mut Self`
fn translate(&mut self, x: f64, y: f64) {
self.p1.x += x;
self.p2.x += x;
self.p1.y += y;
self.p2.y += y;
}
}
This code compiles, while mine does not. Why is this?
Can someone tell me what I am missing here?