Answer the question
In order to leave comments, you need to log in
How to return a value from a struct field in a method?
Hello, maybe the question sounds wildly stupid, but I can not implement such a simple thing as calling two methods on an object.
There is a simple structure with two methods:
pub struct MimeType {
pub extension: String,
pub charset: String,
}
impl MimeType {
pub fn new(extension: String, charset: String) -> MimeType {
return MimeType {
extension,
charset,
};
}
pub fn extension(self) -> String {
return self.extension;
}
pub fn charset(self) -> String {
return self.charset;
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn is() {
let m = MimeType::new(
"test".to_owned(),
"UTF-8".to_owned()
);
assert_eq!("UTF-8", m.charset());
assert_eq!("UTF-8", m.extension());
}
}
error[E0382]: use of moved value: `m`
--> src\mime\mod.rs:35:29
|
29 | let m = MimeType::new(
| - move occurs because `m` has type `mime::MimeType`, which does not implement the `Copy` trait
...
34 | assert_eq!("UTF-8", m.charset());
| --------- `m` moved due to this method call
35 | assert_eq!("UTF-8", m.extension());
| ^ value used here after move
|
note: this function consumes the receiver `self` by taking ownership of it, which moves `m`
--> src\mime\mod.rs:18:20
|
18 | pub fn charset(self) -> String {
| ^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0382`.
error: aborting due to previous error
For more information about this error, try `rustc --explain E0382`.
error: could not compile `r-mime`
To learn more, run the command again with --verbose.
warning: build failed, waiting for other jobs to finish...
error: build failed
Answer the question
In order to leave comments, you need to log in
try to write
pub struct MimeType {
extension: String,
charset: String,
}
impl MimeType {
pub fn new(extension: String, charset: String) -> MimeType {
return MimeType { extension, charset };
}
pub fn extension(&self) -> &String {
return &self.extension;
}
pub fn charset(&self) -> &String {
return &self.charset;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question