
use std::collections::HashMap;
let mut counter: HashMap<_type_, usize> = HashMap::new();
for _value_ in _target_ {
let count = counter.entry(_value_).or_insert(0);
*count += 1;
}Entry が空の場合は default: V を挿入します。その後 Entry の値への参照を返します。
// 使用例
// 文字列に含まれるアルファベットがそれぞれいくつあるか数える
use std::collections::HashMap;
let target = "sasakisaku".chars();
let mut counter: HashMap<char, usize> = HashMap::new();
for value in target {
let count = counter.entry(value).or_insert(0);
*count += 1;
}
println!("{:?}", counter);'a'..'c' のようにアルファベットの Range を作ることが出来ません。error[E0277]: the trait bound `char: std::iter::Step` is not satisfied
--> src/main.rs:2:12
|
2 | for c in 'a'..='d' {
| ^^^^^^^^^ the trait `std::iter::Step` is not implemented for `char`
|
= note: required because of the requirements on the impl of `std::iter::Iterator` for `std::ops::RangeInclusive<char>`
// a ~ d を列挙
for c in (b'a'..=b'd').map(char::from) {
println!("{}", c);
};Vec を作る
let x = vec![0; 5];
println!("{:?}", x);std::T::MIN, std::T::MAX のようにします。
let min_isize = std::isize::MIN;
let max_isize = std::isize::MAX;
println!("isize: {} ~ {}", min_isize, max_isize);
1u8 - 5u8Errorthis arithmetic operation will overflowattempt to compute `1_u8 - 5_u8`, which would overflowthis arithmetic operation will overflow
println!("{}", 1u8.saturating_sub(5u8));Vec<f64>, Vec<f32> をソートするVec<f64> や Vec<f32> をソートしようとすると、以下のようにエラーが発生します。
let mut a: Vec<f64> = Vec::from([0.3, 0.1, 0.8]);
a.sort();Errorthe trait bound `f64: Ord` is not satisfieda.sort(); ^^^^ the trait `Ord` is not implemented for `f64`the trait bound `f64: Ord` is not satisfied
a.sort_by(|x, y| x.partial_cmp(y).unwrap());
println!("{:?}", a);
for n in 500..600 {
if !(2..n).take_while(|i| i * i <= n).any(|i| n % i == 0) {
println!("{}", n);
}
};