https://doc.rust-jp.rs/book-ja/ch08-02-strings.html#内部表現
Vec
2022/2/18 21:40:00
let v1 = vec![1, 2, 3];
let v2:Vec<u32> = v1.iter().map(|x|{x + 1}).collect();
assert_eq!(v1, vec![1, 2, 3]);
assert_eq!(v2, vec![2, 3, 4]);
let v1:Vec<String> = vec![String::from("Hoge"), String::from("Fuga"), String::from("Foo")];
let v2:Vec<String> = v1.iter().map(|x|{format!("{}{}", x, x)}).collect();
assert_eq!(v1, vec![String::from("Hoge"), String::from("Fuga"), String::from("Foo")]);
assert_eq!(v2, vec![String::from("HogeHoge"), String::from("FugaFuga"), String::from("FooFoo")]);
let v1:Vec<String> = vec![String::from("Hoge"), String::from("Fuga"), String::from("Foo")];
//所有権の移動が発生し、v1が使えなくなる
let v2:Vec<String> = v1.into_iter().filter(|x|{x.len() == 3}).collect();
assert_eq!(v1, vec![String::from("Hoge"), String::from("Fuga"), String::from("Foo")]);
assert_eq!(v2, vec![String::from("Foo")]);
let v1:Vec<String> = vec![String::from("Hoge"), String::from("Fuga"), String::from("Foo")];
let v2:Vec<&String> = v1.iter().filter(|x|{x.len() == 3}).collect();
assert_eq!(v1, vec![String::from("Hoge"), String::from("Fuga"), String::from("Foo")]);
assert_eq!(v2, vec![&String::from("Foo")]);
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
println!("{:?}", args);
}
fn main() {
enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("blue")),
SpreadsheetCell::Float(10.12),
];
for r in &row {
match r {
SpreadsheetCell::Int(i) => println!("{}", i),
SpreadsheetCell::Text(s) => println!("{}", s),
SpreadsheetCell::Float(f) => println!("{}", f),
}
}
}
3
blue
10.12
https://doc.rust-jp.rs/book-ja/ch08-01-vectors.html#enumを使って複数の型を保持する
let v = vec![100, 32, 57];
for i in &v {
println!("{}", i);
}
/*
100
32
57
*/
let mut v = vec![100, 32, 57];
for i in &mut v {
*i += 50;
}
for i in &v {
println!("{}", i);
}
/*
150
82
107
*/
ベクタの範囲外の要素を取得しようとした場合、[]
ではプログラムが停止するが、get
ではNone
が返されプログラムが停止しない。
ベクタの要素を不変変数に借用した場合は、そのベクタの要素を変更・追加できなくなる
let mut v = vec![1, 2, 3, 4, 5];
let first = &v[0];
v.push(6);
println!("The first element is: {}", first);
/*
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src\main.rs:23:5
|
21 | let first = &v[0];
| - immutable borrow occurs here
22 |
23 | v.push(6);
| ^^^^^^^^^ mutable borrow occurs here
24 |
25 | println!("The first element is: {}", first);
| ----- immutable borrow later used here
*/
let v1: Vec<i32> = Vec::new();
let v2 = vec![1, 2, 3];
println!("v1:{}", v2[2]); //3