基本介绍

gcmd 组件支持从终端读取用户输入数据,常用于终端交互场景。

相关方法:

  1. func Scan(info ...interface{}) string
  2. func Scanf(format string, info ...interface{}) string

这两个方法都是向终端展示给定的信息,自动读取终端用户输入的信息返回,通过回车符号返回。

Scan 使用

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/os/gcmd"
  5. )
  6. func main() {
  7. name := gcmd.Scan("What's your name?\n")
  8. fmt.Println("Your name is:", name)
  9. }

执行后,交互示例:

  1. > What's your name?
  2. john
  3. > Your name is: john

Scanf 使用

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/os/gcmd"
  5. )
  6. func main() {
  7. name := gcmd.Scan("> What's your name?\n")
  8. age := gcmd.Scanf("> Hello %s, how old are you?\n", name)
  9. fmt.Printf("> %s's age is: %s", name, age)
  10. }

执行后,交互示例:

  1. > What's your name?
  2. john
  3. > Hello john, how old are you?
  4. 18
  5. > john's age is: 18