TAKOYAKING’s blog 一覧

TAKOYAKING’s blog

たこ焼き系

Rust: チルダを展開したい(ホームディレクトリ を取得したい)

パスにチルダ「~」を含んでいると展開してくれないのでcrateを利用してみました。

やりたいこと

チルダを展開する

サンプル

GitHub - netvl/shellexpand: A library for shell-like expansions of variables in strings

format!("{}", shellexpand::tilde("~"))

出力(ユーザー名がtakoyaki, OSがMacの場合)

/Users/takoyaki

戻り値がCowなのでformatを利用するのが良いみたいです。

備考

チルダを利用せずにホームディレクトを取得したいだけならhome_dirを使うのもありです。
ただし、

std::env::home_dir()

は非推奨で以下の非推奨メッセージがでます。

use of deprecated item 'std::env::home_dir': This function's behavior is unexpected and probably not what you want. Consider using the home_dir function from https://crates.io/crates/dirs instead.

代わりにクレートのdirを使ってくれとメッセージがでます。

dirのクレート
https://crates.io/crates/dirs

dirs::home_dir();