I'm using Rust 0.13, and am rather new to Rust.
I have a struct that would like to own a string input, but I have code that would like to work with slices of that string, work.
pub struct Lexer<'a> {
input : Option<String>,
work : &'a str,
...
}
My goal is to pass a string to the struct, have it create its own copy, then to create an initial slice pointing to that string. Ideally, I can now use this slice to manipulate it, as the memory backing the slice won't ever change.
pub fn input(&mut self, input : String) {
self.input = Some(input.clone());
self.work = self.input.unwrap().as_slice();
}
impl<'lex> Iterator<Token> for Lexer<'lex> {
fn next(&mut self) -> Option<Token> {
// ...Do work...
match regex!("\\S").find(self.work) {
Some((0, end)) => {
// Cheap to move the view around
self.work = self.work.slice_from(end);
},
_ => ()
}
// ... Do more work ...
}
}
However, this doesn't work because the lifetime is too short:
error: borrowed value does not live long enough
self.work = self.input.unwrap().as_slice();
^~~~~~~~~~~~~~~~~~~
I'm interpreting this to mean that self.input could change, invalidating self.work's view.
Is this a reasonable interpretation?
Is there a way to specify that these fields are tied to each other somehow?
I think if I could specify that Lexer.input is final this would work, but it doesn't look like Rust has a way to do this.
Edit: sample calling code
let mut lexer = lex::Lexer::new();
lexer.add("[0-9]+", Token::NUM);
lexer.add("\\+", Token::PLUS);
for line in io::stdin().lock().lines() {
match line {
Ok(input) => {
lexer.input(input.as_slice());
lexer.lex();
},
Err(e) => ()
}
}
I think your issue can be solved by adding one more layer. You can have one layer that collects the rules of your lexer, and then you create a new struct that actually does the lexing. This is parallel to how the iterators in Rust are implemented themselves!
struct MetaLexer<'a> {
rules: Vec<(&'a str, u32)>,
}
impl<'a> MetaLexer<'a> {
fn new() -> MetaLexer<'a> { MetaLexer { rules: Vec::new() } }
fn add_rule(&mut self, name: &'a str, val: u32) {
self.rules.push((name, val));
}
fn lex<'r, 's>(&'r self, s: &'s str) -> Lexer<'a, 's, 'r> {
Lexer {
rules: &self.rules,
work: s,
}
}
}
struct Lexer<'a : 'r, 's, 'r> {
rules: &'r [(&'a str, u32)],
work: &'s str,
}
impl<'a, 's, 'r> Iterator for Lexer<'a, 's, 'r> {
type Item = u32;
fn next(&mut self) -> Option<u32> {
for &(name, val) in self.rules.iter() {
if self.work.starts_with(name) {
self.work = &self.work[name.len()..];
return Some(val);
}
}
None
}
}
fn main() {
let mut ml = MetaLexer::new();
ml.add_rule("hello", 10);
ml.add_rule("world", 3);
for input in ["hello", "world", "helloworld"].iter() {
// So that we have an allocated string,
// like io::stdin().lock().lines() might give us
let input = input.to_string();
println!("Input: '{}'", input);
for token in ml.lex(&input) {
println!("Token was: {}", token);
}
}
}
Really, you could rename MetaLexer -> Lexer and Lexer -> LexerItems, and then you'd really match the iterators in the standard lib.
If your question is really how do I keep references to the data read from stdin, that's a different question, and very far from your original statement.
Related
playground
I'm trying to build an abstraction over a file, where the content is stored in memory and a hash is computed before writing it out to the filesystem, which should happen in the close() method.
use std::path::PathBuf;
use sha2::{Digest, Sha256};
fn main() {
let mut fwh = FileWithHash::new(PathBuf::from("somepath.txt"));
fwh.write("first line\n");
fwh.write("second line\n");
fwh.close();
}
struct FileWithHash {
path: PathBuf,
hash: Option<String>,
content: Vec<String>,
pub hasher: Sha256,
}
impl FileWithHash {
pub fn new(path: PathBuf) -> FileWithHash {
FileWithHash {
path,
hash: None,
content: Vec::new(),
hasher: Sha256::new(),
}
}
pub fn write(&mut self, content: &str) {
self.hasher.update(content.as_bytes());
self.content.push(content.to_string());
}
pub fn close(&mut self) {
// compute the final hash
// signature: fn finalize(self) -> Output<Self>;
// it consumes self
// error: cannot move out of `self.hasher` which is behind a mutable reference
self.hash = Some(format!("{:x}", self.hasher.finalize()));
// write the file the path
// ...
}
}
the problem I have is that the self.hasher.finalize() method consumes the hasher which is part of self, which is itself &mut. I think I understand why this doesn't work, but I cannot come up with a reasonable fix.
I've tried extracting the logic into a function like
pub fn compute_hash(hasher: Sha256) -> String {
format!("{:x}", hasher.finalize())
}
but then I run into issues with partially moved values (makes sense).
Any ideas about what the proper pattern should be here?
Thanks for your help.
#justinas, I've tried the Option suggestion.
the methods become
pub fn write(&mut self, content: String) {
match &mut self.hasher {
Some(h) => h.update(content.as_bytes()),
None => {}
}
self.size = self.size + content.len();
self.content.push(content);
}
pub fn close(&mut self) {
self.hash = Some(format!("{:x}", self.hasher.take().unwrap().finalize()));
// write the file the path
// ...
}
Does this look OK to you?
Hi I have the following this tutorial for learning more in depth what can I do with rust so I'm aware that this might now be the proper way to do thing. Here is the repository which contains all the code to take a in depth look. I'm having a global vga writer instance which needs to be safe for data races so using lazy_static I initialize it. What I want to do is is to be able to aquire the lock only when I actually print the string so that I implement fmt::Write on the WrappedWriter instead of the Writer to not obtain the lock over the spin::Mutex when I want to print a string rather I want to obtain the lock after the params were formatted . But when I call this the write function:
crate::vga_buffer::WRITER.write_fmt(args).unwrap();
I get the following error:
Compiling rust_os v0.1.0 (D:\Workspace\Organiztions\home\rust\rust_os)
error[E0055]: reached the recursion limit while auto-dereferencing `vga_buffer::writer::WrappedWriter`
--> src\lib.rs:19:31
|
19 | crate::vga_buffer::WRITER.write_fmt(args).unwrap();
| ^^^^^^^^^ deref recursion limit reached
|
= help: consider adding a `#![recursion_limit="256"]` attribute to your crate (`rust_os`)
error: aborting due to previous error
For more information about this error, try `rustc --explain E0055`.
error: could not compile `rust_os`.
Here is the implementation of the Writer + WrappedWriter
use core::fmt;
use lazy_static::lazy_static;
use volatile::Volatile;
use super::color::*;
use super::screen_character;
use core::ops::{DerefMut, Deref};
// #[allow(dead_code)]
// use crate::serial_print;
// use crate::serial_println;
pub const BUFFER_HEIGHT: usize = 25;
pub const BUFFER_WIDTH: usize = 80;
#[repr(transparent)]
struct Buffer {
chars: [[Volatile<screen_character::ScreenCharacter>; BUFFER_WIDTH]; BUFFER_HEIGHT],
}
pub struct Writer {
column_position: usize,
color_code: ColorCode,
buffer: &'static mut Buffer,
}
impl Writer {
pub fn new(column_position: usize,
color_code: ColorCode) -> Writer {
return Writer {
column_position,
color_code,
buffer: unsafe { &mut *(0xb8000 as *mut Buffer) },
};
}
}
impl Writer {
pub fn write_byte(&mut self, byte: u8) {
match byte {
b'\n' => self.new_line(),
byte => {
if self.column_position >= BUFFER_WIDTH {
self.new_line();
}
let row = BUFFER_HEIGHT - 1;
let col = self.column_position;
let color_code = self.color_code;
self.buffer.chars[row][col].write(screen_character::ScreenCharacter::new(byte, color_code));
self.column_position += 1;
}
}
}
pub fn write_string(&mut self, s: &str) {
for byte in s.bytes() {
match byte {
// printable ASCII byte or newline
0x20..=0x7e | b'\n' => self.write_byte(byte),
// not part of printable ASCII range
_ => self.write_byte(0xfe),
}
}
}
fn new_line(&mut self) {
for row in 1..BUFFER_HEIGHT {
for col in 0..BUFFER_WIDTH {
let current_character = self.buffer.chars[row][col].read();
self.buffer.chars[row - 1][col].write(current_character);
}
}
self.clear_row(BUFFER_HEIGHT - 1);
self.column_position = 0;
}
fn clear_row(&mut self, row_index: usize) {
let blank = screen_character::ScreenCharacter::new(b' ', self.color_code);
for col in 0..BUFFER_WIDTH {
self.buffer.chars[row_index][col].write(blank);
}
}
}
// impl fmt::Write for Writer {
// fn write_str(&mut self, s: &str) -> fmt::Result {
// self.write_string(s);
// Ok(())
// }
// }
struct WrappedWriter {
value: spin::Mutex<Writer>
}
impl fmt::Write for WrappedWriter {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.value.lock().write_string(s);
Ok(())
}
}
impl Deref for WrappedWriter {
type Target = WrappedWriter;
fn deref(&self) -> &Self::Target {
return self;
}
}
impl DerefMut for WrappedWriter {
fn deref_mut(&mut self) -> &mut Self::Target {
return self;
}
}
lazy_static! {
pub static ref WRITER: WrappedWriter = {
let writerInstance = WrappedWriter {
value: spin::Mutex::new(
Writer::new(0, ColorCode::new(Color::Yellow, Color::Black))
)
};
writerInstance
};
}
#[test_case]
fn test_println_output() {
let test_str = "Some test string that fits on a single line";
println!("{}", test_str);
for (char_index, char) in test_str.chars().enumerate() {
let screen_char = WRITER.value.lock().buffer.chars[BUFFER_HEIGHT - 2][char_index].read();
assert_eq!(char::from(screen_char.ascii_character), char);
}
}
Deref + DerefMut Were implemented because I get the following error without them but then again I didn't knew on what should I deref cause I don't actually need to deref from my point of view this are needed because write_fmt gets a mut of self
error[E0596]: cannot borrow data in a dereference of `vga_buffer::writer::WRITER` as mutable
--> src\lib.rs:19:5
|
19 | crate::vga_buffer::WRITER.write_fmt(args).unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
|
= help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `vga_buffer::writer::WRITER`
WrappedWriter currently derefs to itself, which derefs to itself, which derefs to itself, and so on, which is why you reach the recursion limit. You probably want to make it deref to the Writer inside by obtaining a lock.
I keep stumbling on a pattern in my Rust programs that always puts me at odds with the borrow-checker. Consider the following toy example:
use std::sync::{Arc,RwLock};
pub struct Test {
thing: i32,
}
pub struct Test2 {
pub test: Arc<RwLock<Test>>,
pub those: i32,
}
impl Test {
pub fn foo(&self) -> Option<i32> {
Some(3)
}
}
impl Test2 {
pub fn bar(&mut self) {
let mut test_writer = self.test.write().unwrap();
match test_writer.foo() {
Some(thing) => {
self.add(thing);
},
None => {}
}
}
pub fn add(&mut self, addme: i32) {
self.those += addme;
}
}
This doesn't compile because the add function in the Some arm tries to borrow self mutably, which was already borrowed immutably just above the match statement in order to open the read-write lock.
I've encountered this pattern a few times in Rust, mainly when using RwLock. I've also found a workaround, namely by introducing a boolean before the match statement and then changing the value of the boolean in the Some arm and then finally introducing a test on this boolean after the match statement to do whatever it is I wanted to do in the Some arm.
It just seems to me that that's not the way to go about it, I assume there's a more idiomatic way to do this in Rust - or solve the problem in an entirely different way - but I can't find it. If I'm not mistaken the problem has to do with lexical borrowing so self cannot be mutably borrowed within the arms of the match statement.
Is there an idiomatic Rust way to solve this sort of problem?
Use directly the field those, for example with custom type:
use std::sync::{Arc,RwLock};
pub struct Those(i32);
impl Those {
fn get(&self) -> i32 {
self.0
}
fn add(&mut self, n: i32) {
self.0 += n;
}
}
pub struct Test {
thing: Those,
}
pub struct Test2 {
pub test: Arc<RwLock<Test>>,
pub those: Those,
}
impl Test {
pub fn foo(&self) -> Option<Those> {
Some(Those(3))
}
}
impl Test2 {
pub fn bar(&mut self) {
let mut test_writer = self.test.write().unwrap();
match test_writer.foo() {
Some(thing) => {
// call a method add directly on your type to get around the borrow checker
self.those.add(thing.get());
},
None => {}
}
}
}
You either need to end borrow of a part of self, before mutating self
pub fn bar1(&mut self) {
let foo = self.test.write().unwrap().foo();
match foo {
Some(thing) => {
self.add(thing);
},
None => {}
}
}
or directly mutate non borrowed part of self
pub fn bar2(&mut self) {
let test_writer = self.test.write().unwrap();
match test_writer.foo() {
Some(thing) => {
self.those += thing;
},
None => {}
}
}
I have a struct Foo:
struct Foo {
v: String,
// Other data not important for the question
}
I want to handle a data stream and save the result into Vec<Foo> and also create an index for this Vec<Foo> on the field Foo::v.
I want to use a HashMap<&str, usize> for the index, where the keys will be &Foo::v and the value is the position in the Vec<Foo>, but I'm open to other suggestions.
I want to do the data stream handling as fast as possible, which requires not doing obvious things twice.
For example, I want to:
allocate a String only once per one data stream reading
not search the index twice, once to check that the key does not exist, once for inserting new key.
not increase the run time by using Rc or RefCell.
The borrow checker does not allow this code:
let mut l = Vec::<Foo>::new();
{
let mut hash = HashMap::<&str, usize>::new();
//here is loop in real code, like:
//let mut s: String;
//while get_s(&mut s) {
let s = "aaa".to_string();
let idx: usize = match hash.entry(&s) { //a
Occupied(ent) => {
*ent.get()
}
Vacant(ent) => {
l.push(Foo { v: s }); //b
ent.insert(l.len() - 1);
l.len() - 1
}
};
// do something with idx
}
There are multiple problems:
hash.entry borrows the key so s must have a "bigger" lifetime than hash
I want to move s at line (b), while I have a read-only reference at line (a)
So how should I implement this simple algorithm without an extra call to String::clone or calling HashMap::get after calling HashMap::insert?
In general, what you are trying to accomplish is unsafe and Rust is correctly preventing you from doing something you shouldn't. For a simple example why, consider a Vec<u8>. If the vector has one item and a capacity of one, adding another value to the vector will cause a re-allocation and copying of all the values in the vector, invalidating any references into the vector. This would cause all of your keys in your index to point to arbitrary memory addresses, thus leading to unsafe behavior. The compiler prevents that.
In this case, there's two extra pieces of information that the compiler is unaware of but the programmer isn't:
There's an extra indirection — String is heap-allocated, so moving the pointer to that heap allocation isn't really a problem.
The String will never be changed. If it were, then it might reallocate, invalidating the referred-to address. Using a Box<[str]> instead of a String would be a way to enforce this via the type system.
In cases like this, it is OK to use unsafe code, so long as you properly document why it's not unsafe.
use std::collections::HashMap;
#[derive(Debug)]
struct Player {
name: String,
}
fn main() {
let names = ["alice", "bob", "clarice", "danny", "eustice", "frank"];
let mut players = Vec::new();
let mut index = HashMap::new();
for &name in &names {
let player = Player { name: name.into() };
let idx = players.len();
// I copied this code from Stack Overflow without reading the prose
// that describes why this unsafe block is actually safe
let stable_name: &str = unsafe { &*(player.name.as_str() as *const str) };
players.push(player);
index.insert(idx, stable_name);
}
for (k, v) in &index {
println!("{:?} -> {:?}", k, v);
}
for v in &players {
println!("{:?}", v);
}
}
However, my guess is that you don't want this code in your main method but want to return it from some function. That will be a problem, as you will quickly run into Why can't I store a value and a reference to that value in the same struct?.
Honestly, there's styles of code that don't fit well within Rust's limitations. If you run into these, you could:
decide that Rust isn't a good fit for you or your problem.
use unsafe code, preferably thoroughly tested and only exposing a safe API.
investigate alternate representations.
For example, I'd probably rewrite the code to have the index be the primary owner of the key:
use std::collections::BTreeMap;
#[derive(Debug)]
struct Player<'a> {
name: &'a str,
data: &'a PlayerData,
}
#[derive(Debug)]
struct PlayerData {
hit_points: u8,
}
#[derive(Debug)]
struct Players(BTreeMap<String, PlayerData>);
impl Players {
fn new<I>(iter: I) -> Self
where
I: IntoIterator,
I::Item: Into<String>,
{
let players = iter
.into_iter()
.map(|name| (name.into(), PlayerData { hit_points: 100 }))
.collect();
Players(players)
}
fn get<'a>(&'a self, name: &'a str) -> Option<Player<'a>> {
self.0.get(name).map(|data| Player { name, data })
}
}
fn main() {
let names = ["alice", "bob", "clarice", "danny", "eustice", "frank"];
let players = Players::new(names.iter().copied());
for (k, v) in &players.0 {
println!("{:?} -> {:?}", k, v);
}
println!("{:?}", players.get("eustice"));
}
Alternatively, as shown in What's the idiomatic way to make a lookup table which uses field of the item as the key?, you could wrap your type and store it in a set container instead:
use std::collections::BTreeSet;
#[derive(Debug, PartialEq, Eq)]
struct Player {
name: String,
hit_points: u8,
}
#[derive(Debug, Eq)]
struct PlayerByName(Player);
impl PlayerByName {
fn key(&self) -> &str {
&self.0.name
}
}
impl PartialOrd for PlayerByName {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for PlayerByName {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.key().cmp(&other.key())
}
}
impl PartialEq for PlayerByName {
fn eq(&self, other: &Self) -> bool {
self.key() == other.key()
}
}
impl std::borrow::Borrow<str> for PlayerByName {
fn borrow(&self) -> &str {
self.key()
}
}
#[derive(Debug)]
struct Players(BTreeSet<PlayerByName>);
impl Players {
fn new<I>(iter: I) -> Self
where
I: IntoIterator,
I::Item: Into<String>,
{
let players = iter
.into_iter()
.map(|name| {
PlayerByName(Player {
name: name.into(),
hit_points: 100,
})
})
.collect();
Players(players)
}
fn get(&self, name: &str) -> Option<&Player> {
self.0.get(name).map(|pbn| &pbn.0)
}
}
fn main() {
let names = ["alice", "bob", "clarice", "danny", "eustice", "frank"];
let players = Players::new(names.iter().copied());
for player in &players.0 {
println!("{:?}", player.0);
}
println!("{:?}", players.get("eustice"));
}
not increase the run time by using Rc or RefCell
Guessing about performance characteristics without performing profiling is never a good idea. I honestly don't believe that there'd be a noticeable performance loss from incrementing an integer when a value is cloned or dropped. If the problem required both an index and a vector, then I would reach for some kind of shared ownership.
not increase the run time by using Rc or RefCell.
#Shepmaster already demonstrated accomplishing this using unsafe, once you have I would encourage you to check how much Rc actually would cost you. Here is a full version with Rc:
use std::{
collections::{hash_map::Entry, HashMap},
rc::Rc,
};
#[derive(Debug)]
struct Foo {
v: Rc<str>,
}
#[derive(Debug)]
struct Collection {
vec: Vec<Foo>,
index: HashMap<Rc<str>, usize>,
}
impl Foo {
fn new(s: &str) -> Foo {
Foo {
v: s.into(),
}
}
}
impl Collection {
fn new() -> Collection {
Collection {
vec: Vec::new(),
index: HashMap::new(),
}
}
fn insert(&mut self, foo: Foo) {
match self.index.entry(foo.v.clone()) {
Entry::Occupied(o) => panic!(
"Duplicate entry for: {}, {:?} inserted before {:?}",
foo.v,
o.get(),
foo
),
Entry::Vacant(v) => v.insert(self.vec.len()),
};
self.vec.push(foo)
}
}
fn main() {
let mut collection = Collection::new();
for foo in vec![Foo::new("Hello"), Foo::new("World"), Foo::new("Go!")] {
collection.insert(foo)
}
println!("{:?}", collection);
}
The error is:
error: `s` does not live long enough
--> <anon>:27:5
|
16 | let idx: usize = match hash.entry(&s) { //a
| - borrow occurs here
...
27 | }
| ^ `s` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
The note: at the end is where the answer is.
s must outlive hash because you are using &s as a key in the HashMap. This reference will become invalid when s is dropped. But, as the note says, hash will be dropped after s. A quick fix is to swap the order of their declarations:
let s = "aaa".to_string();
let mut hash = HashMap::<&str, usize>::new();
But now you have another problem:
error[E0505]: cannot move out of `s` because it is borrowed
--> <anon>:22:33
|
17 | let idx: usize = match hash.entry(&s) { //a
| - borrow of `s` occurs here
...
22 | l.push(Foo { v: s }); //b
| ^ move out of `s` occurs here
This one is more obvious. s is borrowed by the Entry, which will live to the end of the block. Cloning s will fix that:
l.push(Foo { v: s.clone() }); //b
I only want to allocate s only once, not cloning it
But the type of Foo.v is String, so it will own its own copy of the str anyway. Just that type means you have to copy the s.
You can replace it with a &str instead which will allow it to stay as a reference into s:
struct Foo<'a> {
v: &'a str,
}
pub fn main() {
// s now lives longer than l
let s = "aaa".to_string();
let mut l = Vec::<Foo>::new();
{
let mut hash = HashMap::<&str, usize>::new();
let idx: usize = match hash.entry(&s) {
Occupied(ent) => {
*ent.get()
}
Vacant(ent) => {
l.push(Foo { v: &s });
ent.insert(l.len() - 1);
l.len() - 1
}
};
}
}
Note that, previously I had to move the declaration of s to before hash, so that it would outlive it. But now, l holds a reference to s, so it has to be declared even earlier, so that it outlives l.
The following code doesn't compile:
trait Phone {
fn call(&self);
}
struct IPhone<'a> {
my_str: &'a str
}
impl<'a> Phone for IPhone<'a> {
fn call(&self) {
print!("{}", self.my_str);
}
}
trait Factory<'a, P: Phone> {
fn new_phone(&self, ms: &'a str) -> P;
}
struct IPhoneFactory;
impl<'a> Factory<'a, IPhone<'a>> for IPhoneFactory {
fn new_phone(&self, ms: &'a str) -> IPhone<'a> {
return IPhone {
my_str: ms
};
}
}
fn call_phone<'a, P: Phone, F: Factory<'a, P>>(f: F) {
for _ in 0..10 {
let s = String::new();
let p = f.new_phone(s.as_str());
p.call();
}
}
fn main() {
call_phone(IPhoneFactory);
}
I get the following error:
error: `s` does not live long enough
let p = f.new_phone(s.as_str());
^
note: reference must be valid for the lifetime 'a as defined on the block at 28:53...
fn call_phone<'a, P: Phone, F: Factory<'a, P>>(f: F) {
^
note: ...but borrowed value is only valid for the block suffix following statement 0 at 30:30
let s = String::new();
^
I want to be able to have a factory that returns an abstract class, but when that class takes a reference I can't figure out how to specify the lifetime properly.
You're right about that:
There is no reason for the reference to live as long as the factory, it only needs to live as long as the object the factory is creating (the factory itself doesn't store a reference to the string).
But the bound on call_phone says something different
fn call_phone<'a, P: Phone, F: Factory<'a, P>>(f: F) { ... }
That code says that there's a single lifetime for the whole factory, which will be used for each phone. You want something different, you want to say that f is a good factory for any lifetime:
fn call_phone<..., F: for<'a> Factory<'a, ...>>(f: F) { ... }
The other problem is that in the Factory trait definition:
trait Factory<'a, P: Phone> {
fn new_phone(&self, ms: &'a str) -> P;
}
There's nothing tying lifetime of P to ms. The trait definition allows the returned phone to outlive the string, which should definitely be forbidden for the IPhone implementation! So, to fix it, we add a lifetime parameter to the Phone trait:
trait Phone<'a> {
fn call(&self);
}
But there's still one problem. We can't really write that signature:
fn call_phone<P: ???, F: for<'a> Factory<'a, P<'a>>(f: F) { ... }
Since we want P to be not a type, but rather a family of types (more precisely, a lifetime → type constructor). Remember, the phone in each iteration of loop has a different type (since the lifetime is a part of a type, and lifetimes in different iterations of loops are different).
Ability to express such a signature is planned for the future Rust, but for now, we have to make a workaround and make the phone associated type of Factory trait:
trait Phone<'a> {
fn call(&self);
}
struct IPhone<'a> {
my_str: &'a str
}
impl<'a> Phone<'a> for IPhone<'a> {
fn call(&self) {
println!("{}", self.my_str);
}
}
trait Factory<'a> {
type Output: Phone<'a>;
fn new_phone(&self, ms: &'a str) -> Self::Output;
}
struct IPhoneFactory;
impl<'a> Factory<'a> for IPhoneFactory {
type Output = IPhone<'a>;
fn new_phone(&self, ms: &'a str) -> IPhone<'a> {
IPhone {
my_str: ms
}
}
}
fn call_phone<F: for<'a> Factory<'a>>(f: F) {
for i in 0..10 {
let s = i.to_string();
let p = f.new_phone(&s);
p.call();
}
}
fn main() {
call_phone(IPhoneFactory);
}
Associated type allows the factory to produce only one kind of product, which is maybe what you wanted. If you want different implementations of Factory to have different Outputs, you can achieve this by using phantom types:
trait Phone<'a> {
type Phantom;
fn call(&self);
}
enum IPhonePhantom {}
struct IPhone<'a> {
my_str: &'a str
}
impl<'a> Phone<'a> for IPhone<'a> {
type Phantom = IPhonePhantom;
fn call(&self) {
println!("{}", self.my_str);
}
}
trait Factory<'a, Selector> {
type Output: Phone<'a, Phantom=Selector>;
fn new_phone(&self, ms: &'a str) -> Self::Output;
}
struct MyFactory;
impl<'a> Factory<'a, IPhonePhantom> for MyFactory {
type Output = IPhone<'a>;
fn new_phone(&self, ms: &'a str) -> IPhone<'a> {
IPhone {
my_str: ms
}
}
}
fn call_phone<Selector, F: for<'a> Factory<'a, Selector>>(f: F) {
for i in 0..10 {
let s = i.to_string();
let p = f.new_phone(&s);
p.call();
}
}
fn main() {
call_phone::<IPhonePhantom, _>(MyFactory);
}
The Phantom associated type on the Phone trait is not strictly necessary, it's only needed to tie the phone type to its phantom type and to make sure Factory implementors don't lie.
Your problem is here:
fn call_phone<'a, P: Phone, F: Factory<'a, P>>(f: F) {
// Factory has a lifetime 'a ----------^
// that is at least as long as the scope of call_phone
for _ in 0..10 {
let s = String::new(); // s is born here
let p = f.new_phone(s.as_str());
// new reference ---^
// new_phone definition requires this to have
// the same lifetime 'a as the Factory
p.call();
}
// s is destroyed here, no references to s can
// still exist
} // F is still alive
One thing you can do is passing the &str as a parameter to call_phone, to make sure the reference lives as long as the function:
fn call_phone<'a, P: Phone, F: Factory<'a, P>>(f: F, s: &'a str) {
for _ in 0..10 {
let p = f.new_phone(s);
p.call();
}
}
fn main() {
call_phone(IPhoneFactory, &"hello");
}
Another one is not working with references, but let your struct IPhone own the String