借用のまとめ
Coddyの「R開発者のためのRust」コースのレッスン 20/48。
チャレンジ
簡単archive.rsに2つのAPIを実装します。pub fn prefix<'a>(text: &'a str, count: usize) -> &'a strは、先頭から最大count個のUnicodeスカラー値を返し、同じ領域を借用します。また、pub fn archive(text: String, count: usize) -> Stringは文字列を消費し、その接頭辞に#と元のUTF-8バイト長を続けた文字列を返します。スカラー値の数を超えるcountを指定した場合は、テキスト全体を保持します。0の場合は何も保持しません。入力は、1行目が0以上の数値、2行目が任意のテキストで、その後に改行はありません。solveはarchiveを呼び出し、その結果を返します。archiveは公開ヘルパーと同じ接頭辞の扱いを使用する必要があります。
必要な公開APIを実装し、exercise::solve(input: &str) -> Stringから末尾の改行を付けずに結果を返します。編集可能なコード内で出力しないでください。ロックされたドライバーは必要なAPIを個別に検証し、標準入力をすべて読み取り、返されたテキストを末尾に改行を1つ付けて出力します。
コードはexercise.rsとarchive.rsに記述します。main.rsには提供された入出力コードがあり、編集できません。
自分で試してみよう
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod archive;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 公開APIの検査開始
let data = String::from("犬abé");
assert_eq!(archive::prefix(&data, 2), "犬a");
assert_eq!(archive::prefix(&data, 2).as_ptr(), data.as_ptr());
assert_eq!(archive::prefix(&data, 0), "");
assert_eq!(archive::prefix(&data, 90), data.as_str());
assert_eq!(archive::archive(data, 3), "犬ab#7");
assert_eq!(archive::archive(String::new(), 9), "#0");
// 公開APIの検査終了
println!("{}", exercise::solve(&input));
}
R開発者のためのRustのすべてのレッスン
自分で練習してみよう: Rustオンラインコンパイラ