0
5

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 3 years have passed since last update.

Golangで対話型CLIツールの作り方

Last updated at Posted at 2020-10-02

golangで対話型のCLIツールを作成する。

コマンドを叩くと入力待ちの状態となり、
適切な値を入力するまで無限ループする。

必要なパッケージ

  • bufio
  • os

サンプルコード

package main

import (
	"fmt"
	"bufio"
	"os"
)

func main() {
	fmt.Println("stop と入力して下さい。")
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		if scanner.Text() == "stop" {
			break
		}
		fmt.Println("stop と入力されるまでループします。")
	}
	fmt.Println("終了します。")
}
// このメソッドで入力待ちとなる
scanner.Scan()
// 正常に入力値を受け取ると true を返す
val := scanner.Scan()
fmt.Println(val)
// => true
// 入力された値はこのメソッドで呼び出せる
scanner.Text()
0
5
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
0
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?