部分配列の参照。元メモリと整合性がとれる。
成果物
参考
部分配列の問題
fn main() { let mut s = String::from("hello"); let len = s.len(); s.clear(); }
s.clear()
で文字列長は0になった。なのにlen
は未だhello
だった頃の文字列長5
を保持している。s
とlen
の整合性がとれていない状態となる。
文字列スライス
fn main() { let s = String::from("hello world"); let hello = &s[0..5]; // &s[..5] let world = &s[6..11]; // &s[6..] &s[6..len] let helloworld = &s[0..11]; // &s[..] }
&
は参照。メモリ領域を変更せず読取る。[開始..終了]
で全体から指定した部分だけを参照する。
部分文字列の整合性
fn main() { let mut s = String::from("hello world"); let word = first_word(&s); // error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable s.clear(); println!("{} {}", s, word); } fn first_word(s: &String) -> &str { let b = s.as_bytes(); for (i, &item) in b.iter().enumerate() { if b' ' == item { return &s[..i]; } } &s[..] }
first_word
の引数s
は不変である。(結果も不変を前提としている)。だが、s.clear()
で変更されてしまった。変数s
とword
の整合性がとれなくなる。だが、コンパイルエラーになってくれる。
文字列スライスのほうを先にメモリ解放してしまえば問題ない。
fn main() { let mut s = String::from("hello world"); { let word = first_word(&s); // OK } s.clear(); }
文字列リテラル=スライス
let s = "hello"; // &str型=不変な参照
String→&str
first_word関数の引数を&str
型にすると、String
, &str
両方の型で使える。
fn main() { let mut s = String::from("hello world"); let word = first_word(&s); let word = first_word(&s[..]); println!("{} {}", s, word); } fn first_word(s: &str) -> &str { let b = s.as_bytes(); for (i, &item) in b.iter().enumerate() { if b' ' == item { return &s[..i]; } } &s[..] }
配列のスライス
let a = [1,2,3,4,5]; let slice = &a[1..3];
対象環境
- Raspbierry pi 3 Model B+
- Raspbian stretch 9.0 2018-11-13
- bash 4.4.12(1)-release
$ uname -a Linux raspberrypi 4.19.42-v7+ #1219 SMP Tue May 14 21:20:58 BST 2019 armv7l GNU/Linux
前回まで
- Rustを学んでみたい(プログラミング言語)
- Rustの環境構築
- RustでHelloWorld
- Rustの和訳ドキュメント
- Cargoでプロジェクト作成・ビルド・実行
- クレートとは?
- Rustで関数を使ってみる
- Rustでモジュールを使ってみる
- Rustで乱数を生成する(rand)
- Rustで標準入力する(std::io::stdin().read_line())
- RustでMatch判定する(match)
- Rustでprintとread_lineを1行にする方法
- Rustで数当てゲーム
- クレート名にドット.が使えない
- Rustの変数と可変性(let, mut) error[E0384]: cannot assign twice to immutable variable
x
- Rustのimmutable束縛とconst定数の違い
- RustのREPL、evcxrのインストールに失敗した
- Rustでコンパイルするときの変数未使用warningを消す
- Rustの変数(再代入、再宣言(シャドーイング))
- Rustのシャドーイングについて
- イミュータブルについて(副作用)
- Rustの定数(const)
- Rustのデータ型(数値)
- Rustのデータ型(論理)
- Rustのデータ型(文字)
- Rustのデータ型(タプル)
- Rustのデータ型(配列)
- Rustの関数
- Rustのif式
- Rustのくりかえし文(loop)
- Rustのくりかえし文(while)
- Rustのくりかえし文(for)
- Rustの所有権(ムーブ)
- Rustの所有権(関数)