Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
int
Rust
提交
8ddb9c71
R
Rust
项目概览
int
/
Rust
大约 1 年 前同步成功
通知
1
Star
0
Fork
0
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
DevOps
流水线
流水线任务
计划
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
R
Rust
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
DevOps
DevOps
流水线
流水线任务
计划
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
流水线任务
提交
Issue看板
体验新版 GitCode,发现更多精彩内容 >>
提交
8ddb9c71
编写于
8月 28, 2014
作者:
S
Steve Klabnik
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
Add section about Str trait
上级
bda3ceda
变更
1
隐藏空白更改
内联
并排
Showing
1 changed file
with
32 addition
and
5 deletion
+32
-5
src/doc/guide-strings.md
src/doc/guide-strings.md
+32
-5
未找到文件。
src/doc/guide-strings.md
浏览文件 @
8ddb9c71
...
...
@@ -92,9 +92,33 @@ fn foo(s: String) {
```
If you have good reason. It's not polite to hold on to ownership you don't
need, and it can make your lifetimes more complex. Furthermore, you can pass
either kind of string into
`foo`
by using
`.as_slice()`
on any
`String`
you
need to pass in, so the
`&str`
version is more flexible.
need, and it can make your lifetimes more complex.
## Generic functions
To write a function that's generic over types of strings, use
[
the `Str`
trait
](
http://doc.rust-lang.org/std/str/trait.Str.html
)
:
```
{rust}
fn some_string_length<T: Str>(x: T) -> uint {
x.as_slice().len()
}
fn main() {
let s = "Hello, world";
println!("{}", some_string_length(s));
let s = "Hello, world".to_string();
println!("{}", some_string_length(s));
}
```
Both of these lines will print
`12`
.
The only method that the
`Str`
trait has is
`as_slice()`
, which gives you
access to a
`&str`
value from the underlying string.
## Comparisons
...
...
@@ -134,7 +158,7 @@ println!("{}", s[0]);
This does not compile. This is on purpose. In the world of UTF-8, direct
indexing is basically never what you want to do. The reason is that each
charater can be a variable number of bytes. This means that you have to iterate
chara
c
ter can be a variable number of bytes. This means that you have to iterate
through the characters anyway, which is a O(n) operation.
To iterate over a string, use the
`graphemes()`
method on
`&str`
:
...
...
@@ -147,6 +171,9 @@ for l in s.graphemes(true) {
}
```
Note that
`l`
has the type
`&str`
here, since a single grapheme can consist of
multiple codepoints, so a
`char`
wouldn't be appropriate.
This will print out each character in turn, as you'd expect: first "α", then
"ἰ", etc. You can see that this is different than just the individual bytes.
Here's a version that prints out each byte:
...
...
@@ -154,7 +181,7 @@ Here's a version that prints out each byte:
```
{rust}
let s = "αἰθήρ";
for l in s.
as_bytes().iter
() {
for l in s.
bytes
() {
println!("{}", l);
}
```
...
...
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录