1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rustを始める|guessing_gameで学ぶ(2)

1
Posted at

はじめに

下記の記事の続きになります。

ユーザ入力の処理

io::stdin()
    .read_line(&mut guess)
    .expect("Failed to read line")

println!("You guessed: {}", guess);

:writing_hand_tone2: io::stdin()

  • io モジュールの stdin 関数を呼び出す

:writing_hand_tone2: .read_line(&mut guess)

  • 標準入力ハンドルの 「read_line メソッド」を呼び出しユーザからの入力を取得
  • read_line の引数として &mut guess を可変参照で参照渡しをし、ユーザ入力をどの文字列に格納するかを指示(参照や所有権・借用ルールについての記事
  • io::Result の型を返す

:writing_hand_tone2: .expect("Failed to read line")

  • io::Result の返り値が Err の場合、"Failed to read line" が出力される。

read_line メソッド」は、ユーザが標準入力に入力したものを文字列に(いまの内容を上書きせずに)追加することなので、文字列を引数として渡している

実行

作業ディレクトリに移動して実行 :checkered_flag:

$ cd guessing_game/
$ cargo run

入力を促す表示がされ、入力し、エンターを押下するとPlintln!()のメッセージが表示される
スクリーンショット 2025-09-27 181215.png

さいごに

数当てゲームの序盤が完了 :musical_note:
次回は「秘密の数字を生成する」ためのコードを作成し解読していきます。

参考サイト

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?