Namaran

Code daily. Without assist.

2026-09-10

vowels.rs

use std::rc::Rc;

fn count_vowels(s: &str) -> usize {
    s.chars().filter(|c| "aeiou".contains(*c)).count()
}

fn main() {
    let a = String::from("namaran");
    let b = Box::new(String::from("deref"));
    let c = Rc::new(String::from("coercion"));
    println!("{} {} {}", count_vowels(&a), count_vowels(&b), count_vowels(&c));
}

これは何を出力するでしょうか?

Answer

出力は3 2 4です。count_vowelsは&strしか受け取りませんが、関数の引数は型強制が起きる場所です。&Tを渡すと、コンパイラはT: Derefをたどって型が合うまで*を自動で足します。

&aは&Stringで、String: Deref<Target = str>によって1段で&strになります。&bは&Box<String>なので、BoxからString、Stringからstrと2段たどります。Rc<String>もDeref<Target = String>を実装しているので、同じく2段です。どれも中の文字列を借りるだけで、コピーは起きません。数える母音は、namaranがaの3個、derefがeの2個、coercionがo、e、i、oの4個です。