while trying different ways send vec<u8> function expects &[u8], made "mistake" works. wrote sample code show this:
fn sum(v: &[u8]) -> u8 { let mut s = 0u8; x in v.iter() { s = s + x; } return s; } fn main() { let myarr = [1u8, 2u8, 3u8]; let myvec = vec![1u8, 2u8, 3u8]; println!("{}", sum(&myarr)); println!("{}", sum(&myvec)); } i have few questions in relation this:
- why , how work?
- is there automatic casting between these 2 types?
- does incur penalty or taking memory location of underlying array of vector?
- does mean type of usage (read operations on array of numbers) better use array , not vector api?
let's 1 thing out of way: there no arrays in sum function. rust has 3 related types, , can search here on stack overflow or the rust programming language more information them:
- slices
&[t]. - vectors
vec<t> - arrays
[t; n]
the v argument slice, pointer chunk of data , number of elements.
why , how work? there automatic casting between these 2 types?
the deref trait coming play here. there's implementation of trait looks like:
impl<t> deref vec<t> { type target = [t]; fn deref(&self) -> &[t]; } this means reference vec<t> can act reference [t] , gains of methods target type. deref understood compiler, type able implement it, it's sort of special.
does incur penalty or taking memory location of underlying array of vector?
this zero-cost transformation, why compiler you. it's unusual have compiler expensive.
does mean type of usage better use array , not vector api?
absolutely! 100% of time should accept &[t] instead of &vec<t>. more things vec can provide &[t], , arrays example of that.
Comments
Post a Comment