我创建了一个存储值和对它们的引用的结构,还创建了一种用于添加值和指定生存期的方法。代码示例:
public class EndpointAddRequest : RequestBase
{
[MinLength(4, ErrorMessage = "The number of characters is less than the minimum amount")]
[RegularExpression(RegexConstants.Base64String, ErrorMessage = "Invalid AccessDevice Uid")]
[Required(ErrorMessage = "AccessDevice uid is required")]
}
然后我遇到了编译器错误:
struct Storage<'a> {
owner :Vec<i32>,
links :Vec<&'a i32>
}
impl<'a> Storage<'a> {
fn new() -> Storage<'a> {
Storage {owner: vec![], links: vec![]}
}
fn add_int(&mut self, x :i32) {
self.owner.push(x);
let len = self.owner.len();
let ref_x = match self.owner.get(len-1) {
Some(x) => x,
None => panic!("ERROR")
};
self.links.push(ref_x);
let ref_x = 0;
}
}
fn main() {
let mut store = Storage::new();
store.add_int(1);
store.add_int(2);
}
我可以更正此错误,并为error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
let ref_x = match self.owner.get(len-1) {
^^^
的生命周期self
设置结构。但是在这种情况下,即使完成该方法,'a
也不会被删除。然后,当我尝试两次调用该方法时,出现以下错误:
self
但是如何解决这个矛盾?
也许Rust中有一种更正确的方法,即不仅允许通过所有者访问数据,还可以在结构中存储数据?