[rust学习笔记]切片

切片

除了引用,还有一种不持有所有权的数据类型:切片。
切片允许我们引用集合中某一段连续的元素序列,而不是整个集合。

字符串切片

字符串切片是指向String对象中某个连续部分的引用,他的使用方法如下:

fn main() {
    let s = String::from("hello world");

    let hello = &s[0..5];
    let world = &s[6..11];
}

我们可以使用&s[]指定切片,[]中的数字代表切片的范围,如[2…6]。
下图为字符串切片图解:
在这里插入图片描述

在rust的范围语法…有个语法糖,使用与意思写在下面的注释中:


#![allow(unused_variables)]
fn main() {
let s = String::from("hello");

let slice = &s[0..2];
let slice = &s[..2];//省略第一个数字,表示从0开始。这个表示0到2
let slice = &s[3..];//省略第二个数字,表示一直到最后。这个表示3到最后,也就是3到4
let slice = &s[..];//两个数字都省略,表示全部。也就是0到4.

}

字符串字面量就是切片

字符串字面量直接存储在二进制程序中,&str就是一个不可变引用,所以字符串字面量不可变。

let s="hello";

字符串切片作为参数

有经验的开发者会将&str作为字符串的参数,因为能够同时处理String和&str:

fn first_word(s: &str) -> &str
fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}

fn main() {
    let my_string = String::from("hello world");

    // first_word works on slices of `String`s
    let word = first_word(&my_string[..]);

    let my_string_literal = "hello world";

    // first_word works on slices of string literals
    let word = first_word(&my_string_literal[..]);

    // Because string literals *are* string slices already,
    // this works too, without the slice syntax!
    let word = first_word(my_string_literal);
}

其他类型切片

rust允许其他类型的切片,如&[i32]类型切片:

let a = [1, 2, 3, 4, 5];
let slice = &a[1..3];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值