generics - Convert an Option<&T> to Option<T> -


i have function doing int:

fn some_to_value(src: option<&int>) -> option<int> {     match src {         some(x) => some(*x),         none => none     } } 

and wanted make generic (and still use "int" @ level of caller). ok me if instance of t copied. tried that:

fn some_to_value<t>(src: option<&t>) -> option<t> {     match src {         some(x) => some(*x),         none => none     } } 

i get:

error: cannot move out of dereference of `&`-pointer some(x) => some(*x),                 ^~ 

i fail understand why fails (i'm beginner).

some context: made copy of option, because realized after doing "find" on "hashmap", map immutable long return of "find" (an option containing reference item of map) alive.

the rust language has strong concept of ownership, results in "move vs. copy" scenario (i'm going using terminology answer in one).

a shared reference &t (normally) read-only view of t somewhere in memory. 1 important property you're not allowed invalidate t: &t must point valid t instance.

when write *x you're trying move t out by-value, since t unbounded generic compiler has assume worst: type t not copy , must move ownership, is, by-value use (aka byte copy) not semantic copy, meaning source cannot continue used (see linked answer more explanation of this). moving ownership invalidating source... source inside &t, invalidating illegal!

*x works int because copy, by-value use (aka byte copy) same semantic copy: &int not being invalidated.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -