Skip to main content

terminal

从终端接收用户输入

golang提供了api方便我们从终端接收用户的输入,下面我们重点介绍下 ScanlnScanf

Scanln只有在检测到换行符(\n),你输入的数据才会被录进去

练习

Scanln
package main

import "fmt"

func main() {
//实现功能:键盘录入学生的年龄,姓名,成绩,是否为vip
//方式1:Scanln
var name string
fmt.Printf("请输入学生的姓名:")
//name传入地址的目的:在Scanln函数中,对地址中的值进行改变的时候 实际外面的name也受影响了
fmt.Scanln(&name) //录入数据的时候 类型一定要匹配 因为底层会自动判定类型

var age int
fmt.Printf("请输入学生的年龄:")
fmt.Scanln(&age)

var score float32
fmt.Printf("请输入学生的成绩:")
fmt.Scanln(&score)

var isVip bool
fmt.Printf("是否为vip:")
fmt.Scanln(&isVip)

fmt.Printf("学生的姓名为:%v 年龄为:%v 成绩为:%v 是否为vip:%v",name,age,score,isVip)
}

如果类型输入错误会怎样呢?

Scanf
package main

import "fmt"

func main() {
//实现功能:键盘录入学生的年龄,姓名,成绩,是否为vip
//方式1:Scanf
var name string
var age int
var score float32
var isVip bool
fmt.Printf("请输入学生姓名,年龄, 成绩,是否为vip(单个空格隔开):")
fmt.Scanf("%s %d %f %t",&name,&age,&score,&isVip)
fmt.Printf("学生的姓名为:%v 年龄为:%v 成绩为:%v 是否为vip:%v\n",name,age,score,isVip)
}

tip

可以看到不管是Scanln还是Scanf,只要你输入的数据类型不正确(存在数据类型转换),后面的会直接跳过 给你赋上0值

封装好的工具

https://github.com/scott-x/gutils/tree/master/cmd

API

  • func AddTask(tip string, color int, tasks ...string) string: print the tasks and return the option you selected. If you pass "" to tip, it will use build-in tip, otherwise it will use customed tip; color is a int number, which ranges from 1-7, default 6.
  • func AddQuestion(name, tip, retip, re string) *model.Questions
  • func Exec() map[string]string: return the result with map
  • func AskQuestion(tip string) string
  • func Info(str string): print info
  • func Warning(str string): print warning info
  • func Trim(value string) string: trim space of the value received from terminal
  • func SelectOne(desc, tip string, color_option int, t model.Tasker) int: select one item from slice, return the index of the slice, if invalid return -1, see example

示例

package main

import (
"fmt"
"github.com/scott-x/gutils/cmd"
)

func main() {
// option := cmd.AddTask("swmiming", "eating", "sleeping") detatched
option := cmd.AddTask("", 7, "swmiming", "eating", "sleeping")
switch option {
case "1":
//do something
task1()
//anycode here ...
case "2":
//do something
default:
//do something
}
}

func task1() {
cmd.AddQuestion("name", "What's your name ? ", "Please input correct name: ", "^[a-z]+")
cmd.AddQuestion("age", "What's your age ? ", "Please input correct age: ", "^[0-9]{2}$")
answers := cmd.Exec()
fmt.Println(answers)
}