0
点赞
收藏
分享

微信扫一扫

Rust基本数据类型-切片

江南北 2024-04-25 阅读 12

一、切片是什么,怎么用

1、切片是什么

切片并不是 Rust 独有的概念,在 Go 语言中就非常流行,它允许你引用集合部分连续的元素序列,而不是引用整个集合。

对于字符串而言,切片就是对 String 类型中某一部分的引用,它看起来像这样,记得是引用&

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

let hello = &s[0..5];//区间是左闭右开
let world = &s[6..11];

用图来看是这样
1111
但是需要注意的是,切片取索引下标的时候,要将索引放置正确的位置上,比如


// 修复代码中的错误
fn main() {
  let s = String::from("中国人");
  let a = &s[0..2];
  println!("{}",a);
 
}
   Compiling world_hello v0.1.0 (/Users/guilinhuang/Desktop/RustProject/world_hello)
    Finished release [optimized] target(s) in 0.21s
     Running `target/release/world_hello`
thread 'main' panicked at src/main.rs:5:13:
byte index 2 is not a char boundary; it is inside '中' (bytes 0..3) of `中国人`

如何正确便利这种UTF-8字符串,给几个方法

for c in "中国人".chars() {
    println!("{}", c);
}

在Rust中,如果是字符类型,一个字符占4个字节,要与字符串区分


fn main() {
    let arr: [char; 3] = ['中', '国', '人'];

    let slice = &arr[..2];
    assert!(std::mem::size_of_val(slice) == 8);
}
举报

相关推荐

0 条评论