#![allow(dead_code)]
use std::os::raw::c_void;
use std::marker::PhantomData;
pub struct Context<'a> {
name: String,
ctx: *mut c_void,
_ctx: PhantomData<&'a c_void>,
}
impl<'a> Context<'a> {
pub fn new(name: String) -> Self {
Self {
name,
ctx: std::ptr::null_mut(),
_ctx: PhantomData,
}
}
pub fn get_device(&'a self) -> Device<'a> {
Device {
dev: std::ptr::null_mut(),
_dev: PhantomData
}
}
}
pub struct Device<'a> {
dev: *mut c_void,
_dev: PhantomData<&'a c_void>,
}
impl<'a> Device<'a> {
pub fn get_sub_device(&'a self, sub_name: String) -> SubDevice<'a> {
SubDevice {
name: sub_name,
handle: std::ptr::null_mut(),
_handle: PhantomData
}
}
}
pub struct SubDevice<'a> {
name: String,
handle: *mut c_void,
_handle: PhantomData<&'a c_void>,
}
impl<'a> SubDevice<'a> {
pub fn name(&'a self) -> &'a str {
&self.name
}
}
pub struct Manager<'a> {
ctx: Context<'a>,
dev: Option<Device<'a>>,
sub_devs: Vec<SubDevice<'a>>,
}
impl<'a> Manager<'a> {
pub fn new(name: String) -> Self {
Manager {
ctx: Context::new(name),
dev: None,
sub_devs: vec![],
}
}
pub fn open_device(&'a mut self) {
let dev = self.ctx.get_device();
self.dev = Some(dev);
}
pub fn open_sub_device(&mut self, sub_name: String) -> Result<(), String> {
match &mut self.dev {
Some(dev) => {
let sub_dev = dev.get_sub_device(sub_name);
self.sub_devs.push(sub_dev);
Ok(())
}
None => {
Err("Not open".to_string())
}
}
}
pub fn sub_devs(&'a self) -> &'a Vec<SubDevice<'a>> {
&self.sub_devs
}
}
fn main() {
let mut manager = Manager::new("TheManager".to_string());
manager.open_device();
for i in 1..10 {
let name = format!("TheSubDev{}", i);
let _ = manager.open_sub_device(name);
}
let sub_devs = manager.sub_devs();
for sub in sub_devs {
println!("{}", sub.name());
}
}
Errors:
Compiling playground v0.0.1 (/playground)
error: lifetime may not live long enough
--> src/main.rs:79:31
|
62 | impl<'a> Manager<'a> {
| -- lifetime `'a` defined here
...
76 | pub fn open_sub_device(&mut self, sub_name: String) -> Result<(), String> {
| - let's call the lifetime of this reference `'1`
...
79 | let sub_dev = dev.get_sub_device(sub_name);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'1` must outlive `'a`
error[E0499]: cannot borrow `manager` as mutable more than once at a time
--> src/main.rs:99:17
|
96 | manager.open_device();
| ------- first mutable borrow occurs here
...
99 | let _ = manager.open_sub_device(name);
| ^^^^^^^
| |
| second mutable borrow occurs here
| first borrow later used here
error[E0502]: cannot borrow `manager` as immutable because it is also borrowed as mutable
--> src/main.rs:102:20
|
96 | manager.open_device();
| ------- mutable borrow occurs here
...
102 | let sub_devs = manager.sub_devs();
| ^^^^^^^
| |
| immutable borrow occurs here
| mutable borrow later used here
Some errors have detailed explanations: E0499, E0502.
For more information about an error, try `rustc --explain E0499`.
error: could not compile `playground` (bin "playground") due to 3 previous errors