Rustの練習を兼ねて、自作の小さなPythonパッケージをRustで書き直している話

Rustの練習を兼ねて、自作の小さなPythonパッケージをRustで書き直している話

Event:

Rust、何もわからない… #15

Presented:

2026/10/14 nikkie

お前、誰よ

  • nikkie(にっきー)、 Python を書きます(小さなOSS公開、PyCon JP登壇)

  • 機械学習エンジニア [1] ・Speeda AI Agent 開発(A2A・MCP・Slackbot 提供)

../_images/uzabase-white-logo.png

モチベーション:Rust製ツールチェインの盛り上がり

  • Astralによる uv・Ruff・ty に 物申したい

  • pnpm(v12からRust実装)が面白い [2]

自作Pythonパッケージ sampleproject-rs

  • Pythonパッケージのサンプル sampleproject (チュートリアル例)

  • Rust版sampleproject-rsを自作(maturin、PyO3)

println! だけです
$ uvx --from sampleproject-rs@0.2.3 sample
Call your main application code here

8月のPyCon JP 2026より

Rust core化したsampleproject-rs v0.3

.
├── Cargo.toml  # workspace設定
├── pyproject.toml  # bindings-pyを見てPythonパッケージにする(maturin)
├── sample-core/  # Rust core
│   ├── Cargo.toml
│   └── src
│       └── lib.rs
├── bindings-py/  # sample-coreに依存 + PyO3
└── bindings-wasm/  # sample-core + wasm-bindgen

自作の小さなPythonパッケージをRust core化!

  • 賢いAI(6 Solや6.1 Sol)に書き換えてもらい、私専用教材として参照

  • 補完を切り、質問しまくって 写経 している

  • GitHub ActionsはAIに任せた

学び1: String と &str の使い分け

返り値の String と &str は何が違う?
pub fn extract_json(markdown: &str) -> Option<String> { }

pub fn extract_json(markdown: &str) -> Option<&str> { }

引数の型は &str

fn first_word(s: &str) -> &str {
「APIをより一般的で有益なものにできる」
let word1 = first_word(&String::from("hello world"));  // Stringへの参照を渡す

let word2 = first_word("hello world");   // 文字列リテラル(&str)を渡す

返り値: String も &str もある

  • String:新しい文字列を 作って返す

  • &str:入力の 部分文字列 (参照して返す)

pub fn to_snake_case(camel_case_str: &str) -> String { }

pub fn extract_json(markdown: &str) -> Option<&str> { }

学び2: Result の扱い

let input = args
    .input  // clap_stdin::FileOrStdin
    .contents()  // Result<T, StdinError>
    .map_err(|e| PyRuntimeError::new_err(e.to_string()))?;

Result は 消費 される

  • Result の概念は発表を見聞きして理解していた(つもり)

  • Rustで書いてみて消費に気づいた

    (略)動作対象である result を 消費 してしまう(『プログラミングRust 第2版』7.2)

map_err() という選択

leaving an Ok value untouched.

let input = args.input.contents()
    .map_err(|e| PyRuntimeError::new_err(e.to_string()))?;

まとめ🌯Rustの練習を兼ねて、自作の小さなPythonパッケージをRustで書き直している話

  • String は 新しい文字列 を作る、 &str は 部分文字列

  • Result はメソッド選択によっては 消費 されることに注意

ご清聴ありがとうございました!

参考:配布の経験とRust core化

参考:文字列とResult