- Rust Programming By Example
- Guillaume Gomez Antoni Boucher
- 244字
- 2021-07-02 19:13:00
Slices
Arrays are fixed-size, but if we want to create a function that works with arrays of any size, we need to use another type: a slice.
A slice is a view into a contiguous sequence: it can be a view of the whole array, or a part of it. Slices are fat pointers, in addition to the pointer to the data, they contain a size. Here's a function that returns a reference to the first element of a slice:
fn first<T>(slice: &[T]) -> &T { &slice[0] }
Here, we use a generic type without bound since we don't use any operation on values of the T type. The &[T] parameter type is a slice of T. The return type is &T, which is a reference on values of the T type. The body of the function is &slice[0], which returns a reference to the first element of the slice. Here's how to call this function with an array:
println!("{}", first(&array));
We can create slice for only a portion of an array, as shown in the following example:
println!("{}", first(&array[2..]));
&array[2..] creates a slice that starts at the 2 index until the end of the array (hence no index after ..). Both indices are optional, so we could also write &array[..10] for the first 10 elements of the array, &array[5..10] for the elements with the 5 to 9 index (inclusive), or &array[..] for all the elements.
- 智慧場(chǎng)館與智慧學(xué)習(xí)
- 公共圖書館文獻(xiàn)信息資源政府采購
- 檔案保護(hù)技術(shù)
- 檔案檢索: 理論與方法
- 現(xiàn)代圖書館全面質(zhì)量管理與創(chuàng)新服務(wù)研究
- 河南省博物院鎮(zhèn)館之寶
- 構(gòu)筑閱讀天堂:圖書館服務(wù)設(shè)計(jì)探索
- 圖書情報(bào)專業(yè)碩士培養(yǎng)研究與實(shí)踐
- 中國古典文獻(xiàn)學(xué)(東北師范大學(xué)文學(xué)院學(xué)術(shù)史文庫)
- 校勘學(xué)釋例(中國文化叢書·經(jīng)典隨行)
- 檔案智慧化管理與開發(fā)利用的探索研究
- 高校圖書館休閑功能開發(fā)研究
- 高校圖書館工具書管理與服務(wù)研究
- 高校圖書館創(chuàng)新服務(wù)(谷臻小簡·AI導(dǎo)讀版)
- 中國圖書館轉(zhuǎn)型風(fēng)險(xiǎn)研究