2.6 Rust Slice Type
字符串操作
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
Because we need to go through the String element by element and check whether a value is a space, we’ll convert our String to an array of bytes using the as_bytes method
For now, know that iter is a method that returns each element in a collection and that enumerate wraps the result of iter and returns each element as part of a tuple instead. The first element of the tuple returned from enumerate is the index, and the second element is a reference to the element. This is a bit more convenient than calculating the index ourselves.
Because the enumerate method returns a tuple, we can use patterns to destructure that tuple, just like everywhere else in Rust. So in the for loop, we specify a pattern that has i for the index in the tuple and &item for the single byte in the tuple. Because we get a reference to the element from .iter().enumerate(), we use & in the pattern.
Inside the for loop, we search for the byte that represents the space by using the byte literal syntax. If we find a space, we return the position. Otherwise, we return the length of the string by using s.len()
fn main() {
let mut s = String::from("hello world");
let _word = first_word(&s); // word will get the value 5
println!("{},{}",s,_word);
s.clear(); // this empties the String, making it equal to ""
// word still has the value 5 here, but there's no more string that
// we could meaningfully use the value 5 with. word is now totally invalid!
}
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
字符串切片
str[index..end_position]
index:字符索引位置,从0开始
end_position:字符位置,从1开始
let s = String::from("hello world");
let hello = &s[..];
let world = &s[..];

With Rust’s .. range syntax, if you want to start at the first index (zero), you can drop the value before the two periods. In other words, these are equal:
let s = String::from("hello");
let slice = &s[..];
let slice = &s[..];
By the same token, if your slice includes the last byte of the String, you can drop the trailing number. That means these are equal:
let s = String::from("hello");
let len = s.len();
let slice = &s[..len];
let slice = &s[..];
You can also drop both values to take a slice of the entire string. So these are equal:
let s = String::from("hello");
let len = s.len();
let slice = &s[..len];
let slice = &s[..];
Note: String slice range indices must occur at valid UTF-8 character boundaries. If you attempt to create a string slice in the middle of a multibyte character, your program will exit with an error.
切片字符串操作
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[..i];
}
}
&s[..]
}
第一种方式为直接对字符串本身进行操作,没有第二个变量产生,切片则是新定义了一个变量,指向了原字符串的部分内容。当作用域发生变化时,它们的不同就会显现出来。
下面这一段代码是正确的
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear(); // error!
println!("the first word is: {}", word);
}
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
然而官网上则说这段代码是有问题的,可能是rust版本升级后此处做了改动

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);
println!("{}",word);
}
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[..i];
}
}
&s[..]
}
2.6 Rust Slice Type的更多相关文章
- 深度解密Go语言之Slice
目录 当我们在说 slice 时,到底在说什么 slice 的创建 直接声明 字面量 make 截取 slice 和数组的区别在哪 append 到底做了什么 为什么 nil slice 可以直接 a ...
- golang 数组以及slice切片
老虞学GoLang笔记-数组和切片 数组 Arrays 数组是内置(build-in)类型,是一组同类型数据的集合,它是值类型,通过从0开始的下标索引访问元素值.在初始化后长度是固定的,无法修改其 ...
- go基础之基本数据结构(数组、slice、map)
go基本的数据结构有数组.slice.map,高级数据结构为结构体为用户自定义类型.本片文章主要讲解三大基本数据结构. 数组 slice Map 数组 数组是包含单个类型的元素序列,但是长度固定的数据 ...
- golang ----array and slice
Go Slices: usage and internals Introduction Go's slice type provides a convenient and efficient mean ...
- egg源码浅析一npm init egg --type=simple
要egg文档最开始的时候,有这样的几条命令: 我们推荐直接使用脚手架,只需几条简单指令,即可快速生成项目: $ mkdir egg-example && cd egg-example ...
- slice使用了解
切片 什么是slice slice的创建使用 slice使用的一点规范 slice和数组的区别 slice的append是如何发生的 复制Slice和Map注意事项 什么是slice Go中的切片,是 ...
- Go - 内置函数大全
Package builtin import "builtin" Overview Index Overview ▾ Package builtin provides docume ...
- 深入学习golang(3)—类型方法
类型方法 1. 给类型定义方法 在Go语言中,我们可以给任何类型(包括内置类型,但不包括指针和接口)定义方法.例如,在实际编程中,我们经常使用[ ]byte的切片,我们可以定义一个新的类型: type ...
- golang的"..."备忘
1. 用于数组: 表示长度与元素个数相同. 在golang中数组的长度是类型的一部分,不同长度,不同类型. 2. 用于参数: 用于形参表示可变参数. 用于实参表示直接传递. 具体解释参数见官方文档: ...
随机推荐
- ubuntu 16.04启用root和ssh登录
1.设置用户密码 sudo passwd root 2.vim /usr/share/lightdm/lightdm.conf.d/50-ubuntu.conf 末尾添加:greeter-show-m ...
- 编写高质量代码改善C#程序的157个建议——建议91:可见字段应该重构为属性
建议91:可见字段应该重构为属性 字段和属性的本质区别就是属性是方法. 查看下面这个Person类型: class Person { public string Name { get; set; } ...
- JS 前端构建工具gulpjs的使用介绍及技巧
gulpjs是一个前端构建工具,与gruntjs相比,gulpjs无需写一大堆繁杂的配置参数,API也非常简单,学习起来很容易,而且gulpjs使用的是nodejs中stream来读取和操作数据,其速 ...
- [Lua快速了解一下]Lua的函数
-recurrsive function fib(n) end ) + fib(n - ) end -closure 示例一 function newCounter() return function ...
- 深入理解java虚拟机(十) Java 虚拟机运行时栈帧结构
运行时栈帧结构 栈帧(Stack Frame) 是用于虚拟机执行时方法调用和方法执行时的数据结构,它是虚拟栈数据区的组成元素.每一个方法从调用到方法返回都对应着一个栈帧入栈出栈的过程. 每一个栈帧在编 ...
- Duplicate entry '127' for key 'PRIMARY'的解决方法
如果这个时候数据表里面没有数据,而且我们用使用 INSERT INTO VALUES 这样的语句插入,就会提示 Duplicate entry '127' for key 'PRIMARY'
- [JQuery]ScrollMe滚动特效插件
最近考完试,一切顺利,昨晚闲着无聊把最近要用的一个插件翻译了一下:ScrollMe. (╯‵□′)╯︵┻━┻地址请戳: /* ScrollMe -李明夕翻译(╯‵□′)╯︵┻━┻ */ ScrollM ...
- nej+regular环境使用es6的低成本方案
本文来自 网易云社区 . 希望在生产环境中使用es6/7,babel应该是最普遍的选择.这是babel官网中,它对自己的定义: Babel 自带了一组 ES2015 语法转化器.这些转化器能让你现在就 ...
- 序列(DP)(组合数)
这是一个DP题. 我们设\(f[i][j][k]\)表示\(i\)序列长度中放入了\(j\)个元素,其中\(k\)是限定的众数的个数:状态转移方程是 \[f[k][i][j]=f[k][i-1][j- ...
- nowcoder(牛客网)OI测试赛2 解题报告
qwq听说是一场普及组难度的比赛,所以我就兴高采烈地过来了qwq 然后发现题目确实不难qwq.....但是因为蒟蒻我太蒻了,考的还是很差啦qwq orz那些AK的dalao们qwq 赛后闲来无事,弄一 ...