rust - Give caller ownership of local variables that depend on each other -


here's minimal reproduction of problem:

fn str_to_u8(s: &str) -> &[u8] {     let vector = s.chars().map(|c| c u8).collect::<vec<u8>>();     let slice = vector.as_slice();     slice } 

the compiler says vector doesn't live long enough, makes sense. there way force vector "move" slice when caller takes ownership of slice takes ownership of vector?

(copied my answer related still different question.)

you're trying return borrow created in , owned function. impossible. no, there no way around it; can't somehow extend lifetime of vector, returning vector borrow won't work. really. 1 of things rust designed absolutely forbid.

if want transfer out of function, 1 of 2 things must true:

  1. it being stored somewhere outside function outlive current call (as in, given borrow argument; returning doesn't count).

    to expand on this, change function fn str_to_u8<'a, 'b>(s: &'a str, vector: &'b mut vec<u8>) -> &'b [u8]. allow vector survive function , let safely return slice it.

    note: code-smelly alternative leak vector. involves forgetting vector , unsafely casting slice &'static [u8] (i.e. promise compiler live forever). this, obviously, leak heap allocation.

    you store vector in global or something, should option of absolute last resort; rust hates globals.

  2. you returning ownership, not borrowed reference. so, function return vec<u8>, caller slice.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -