1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Rustでプログレスバーを表示する

Posted at

現在フリーランスエンジニアとして活動していて、今今携わっている案件ではRustとTauriを使ってExcelファイルを出力するデスクトップアプリを開発しています。

メンテナンス作業を行うために簡単なバッチ処理を実装しているのですが、バッチ処理の進捗状況を表示するためにプログレスバーを利用しようと思い、Rustでプログレスバーを表示する方法を調べました。

Rustにもプログレスバーを表示するためのクレートがいくつかありますが、今回は最もダウンロード数が多く、開発も活発そうなindicatifを使用します。

早速、indicatifを使ってプログレスバーを表示するサンプルコードを載せます。

Cargo.toml
[dependencies]
indicatif = "0.17.3"
Rust
use std::thread;
use std::time::Duration;

use indicatif::{ProgressBar, ProgressStyle};

// プログレスバーの長さを指定してプログレスバーを作成
let pb = ProgressBar::new(100);
// プログレスバーで表示する文字列を指定
pb.set_style(ProgressStyle::default_bar()
    .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({eta}) \n {msg}")?
    .progress_chars("#>-"));

for _ in 0..100 {
    thread::sleep(Duration::from_millis(5));
    // プログレスバーの進捗位置を繰り上げる
    pb.inc(1);
}
// プログレスバーを終了しメッセージを設定する
pb.finish_with_message("正常終了しました。");
  [00:00:05] [########################################] 100/100 (0s) 
 正常終了しました。

ちょっとハマったこととして、pb.finish_with_message("正常終了しました。");を呼び出しているのに、完了後のメッセージである「正常終了しました。」を表示しなかったというのがありました。

結局原因はプログレスバーのテンプレート文字列の設定(.template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({eta}) \n {msg}")?)で当初{msg}を含めていなかったのが理由で、挿入したら無事メッセージを表示できるようになりました。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?