lifetime

Using str and String interchangably

喜你入骨 提交于 2020-02-03 04:46:47
问题 Suppose I'm trying to do a fancy zero-copy parser in Rust using &str , but sometimes I need to modify the text (e.g. to implement variable substitution). I really want to do something like this: fn main() { let mut v: Vec<&str> = "Hello there $world!".split_whitespace().collect(); for t in v.iter_mut() { if (t.contains("$world")) { *t = &t.replace("$world", "Earth"); } } println!("{:?}", &v); } But of course the String returned by t.replace() doesn't live long enough. Is there a nice way

lifetime bound on associated type is rejected although it seems valid

三世轮回 提交于 2020-01-30 05:44:08
问题 I have a piece of code that does not compile and that can be reduced to this snippet: use std::error::Error; use std::convert::TryFrom; // A trait that provides methods for parsing data into a type T. pub trait Deserializable<T> { // some methods } pub struct MyBuffer<'a> { inner: &'a [u8] } impl<'a, T> Deserializable<T> for MyBuffer<'a> where T: TryFrom<&'a [u8]>, <T as TryFrom<&'a [u8]>>::Error: Error + Sync + Send + 'static { // some methods to implement } fn main() {} The compiler rejects

Textfile-parsing function fails to compile owing to type-mismatch error

我只是一个虾纸丫 提交于 2020-01-24 19:10:27
问题 I'm trying to parse a simple config text file, which contains one three-word entry per line, laid out as follows: ITEM name value ITEM name value //etc. I've reproduced the function which does the parsing (and the subsequent compilation error) here (and on the Rust Playpen): pub fn parse(path: &Path) -> config_struct { let file = File::open(&path).unwrap(); let reader = BufReader::new(&file); let line_iterator = reader.lines(); let mut connection_map = HashMap::new(); let mut target_map =

Return reference with lifetime of self

天大地大妈咪最大 提交于 2020-01-23 07:59:46
问题 I'd like to write some code like the following: struct Foo { foo: usize } impl Foo { pub fn get_foo<'a>(&'a self) -> &'self usize { &self.foo } } But this doesn't work, failing with invalid lifetime name: 'self is no longer a special lifetime . How can I return a reference that lives as long as the object itself? 回答1: You don't want the reference to live exactly as long as the object. You just want a borrow on the object (quite possibly shorter than the entire lifetime of the object), and you

Return reference with lifetime of self

前提是你 提交于 2020-01-23 07:59:06
问题 I'd like to write some code like the following: struct Foo { foo: usize } impl Foo { pub fn get_foo<'a>(&'a self) -> &'self usize { &self.foo } } But this doesn't work, failing with invalid lifetime name: 'self is no longer a special lifetime . How can I return a reference that lives as long as the object itself? 回答1: You don't want the reference to live exactly as long as the object. You just want a borrow on the object (quite possibly shorter than the entire lifetime of the object), and you

Use of variable in own initializer

余生长醉 提交于 2020-01-22 17:07:05
问题 [basic.scope.pdecl]/1 of the C++20 standard draft had the following (non-normative) example in a note (partial quote from before the merge of pull request 3580, see answer to this question): unsigned char x = x; [...] x is initialized with its own (indeterminate) value. Does this actually have well-defined behavior in C++20? Generally the self-initialization of the form T x = x; has undefined behavior by virtue of x 's value being indeterminate before initialization is completed. Evaluating

Why do I get the error “cannot borrow x as mutable more than once”?

喜欢而已 提交于 2020-01-21 19:38:11
问题 I'm implementing a parser in Rust. I have to update the index for the lookahead, but when I call self.get() after self.current() I get an error: cannot borrow *self as mutable more than once at a time It's confusing since I'm new to Rust. #[derive(Debug)] pub enum Token { Random(String), Undefined(String), } struct Point { token: Vec<Token>, look: usize, } impl Point { pub fn init(&mut self){ while let Some(token) = self.current(){ println!("{:?}", token); let _ = self.get(); } } pub fn

problem with delegate

。_饼干妹妹 提交于 2020-01-21 15:24:50
问题 I've made this to call unmanaged function from C code. pCallback is a function pointer so on the managed side is a delegate. [DllImport("MyDLL.dll")] public static extern Result SetCallback( IntPtr handle, Delegate pCallback, CallbackType Type); Now I am setting public delegate void pfnCallback(uint PromptID, ttsEventType evt, IntPtr lData); public Form1() { pfnCallback cb = new pfnCallback(cback); (...) Wrapper.SetCallback(handle, cb, IntPtr.Zero, CallBackType.DEFAULT); (...) } It gives my

Extend lifetime of variable

倖福魔咒の 提交于 2020-01-19 14:13:26
问题 I'm trying to return a slice from a vector which is built inside my function. Obviously this doesn't work because v 's lifetime expires too soon. I'm wondering if there's a way to extend v 's lifetime. I want to return a plain slice, not a vector. pub fn find<'a>(&'a self, name: &str) -> &'a[&'a Element] { let v: Vec<&'a Element> = self.iter_elements().filter(|&elem| elem.name.borrow().local_name == name).collect(); v.as_slice() } 回答1: You can't forcibly extend a value's lifetime; you just

Rust Borrow checker only complains about borrowing as mutable multiple times when a function that returns a reference with the same lifetime assigned

做~自己de王妃 提交于 2020-01-15 09:20:10
问题 I'm having problem with some Rust code where I'm being allowed to borrow something as mutable more than once on certain conditions (first confusing part), but not others. I've written the following example to illustrate: (Playground) struct NoLifetime {} struct WithLifetime <'a> { pub field: &'a i32 } fn main() { let mut some_val = NoLifetime {}; borrow_mut_function(&mut some_val); borrow_mut_function(&mut some_val); // Borrowing as mutable for the second time. let num = 5; let mut life_val =