How to define / edit a struct istance field with a method?
How to define / edit a struct istance field with a method?
Let's say I have a struct Event
which implements the method permalink
:
struct Event {
base_url: String,
rel_permalink: String,
permalink: String,
title: String,
}
impl Event {
fn permalink(&self) -> String {
let permalink = format!("{}{}", self.base_url, self.rel_permalink);
permalink
}
}
The method takes 2 fields of the struct and the target would be to return the definition of another field.
Later I instantiate an event1: Event
:
let event1 = Event {
base_url: base_url,
rel_permalink: rel_permalink.to_string(),
title: node.value().name().to_string(),
permalink = permalink(),
};
Essentially I would like the field permalink
to be the value returned by the method permalink
, is something like this possible, is this correct?
I couldn't find something similar in the docs..
Pheraps using an associated function as constructor would be a better way to handle a similar situation?
Thank you so much!
You're viewing a single thread.
Hmm, yeah, I'd use a constructor method:
impl Event { pub fn new(base_url: String, rel_permalink: String, title: String) -> Self { let permalink = format!("{}{}", self.base_url, self.rel_permalink); Self { base_url, rel_permalink, title, permalink, }; } // ... }
Then you'd instantiate it like so:
let title = node.value().name().to_string(); let event = Event::new(base_url, rel_permalink.to_string(), title);
3 0 ReplyIs it really valid to callpermalink()
in that context, since it requires&self
? There's noself
in that context afaik. Can't test it now but it looks suspiciousEDIT: Invalid since the comment was updated
1 0 ReplySorry, I posted the comment, then realized that problem. 😅
2 0 Reply