package main
import (
"fmt"
"strconv"
"strings"
)
//1.任务的增加
// 具体多少任务不确定,放在一个切片中[]map[string]string
//单个任务放在一个map中 map[string][string]
const (
id = "id"
name = "name"
startTime = "start_time"
endTime = "end_time"
status = "status"
user = "user"
)
const (
statusNew = "新创建"
statusModify = "已修改"
)
var todos = []map[string]string{
{id: "1", name: "上课", startTime: "12:30", status: statusNew, user: "001"},
{id: "2", name: "做操", startTime: "12:30", status: statusNew, user: "001"},
{id: "3", name: "学习", startTime: "12:30", status: statusNew, user: "001"},
{id: "4", name: "学习", startTime: "12:30", status: statusNew, user: "001"},
}
func input(param string) string {
var text string
fmt.Print(param)
fmt.Scan(&text)
return text
}
func initInfo() map[string]string {
todo := map[string]string{
id: strconv.Itoa(genId()),
name: "",
startTime: "",
endTime: "",
status: statusNew,
user: "",
}
return todo
}
func genId() int {
var rt int
//int类型的值类型为0
for _, todo := range todos {
id, _ := strconv.Atoi(todo[id])
if rt < id {
rt = id + 1
}
}
return rt
}
func addInfo() {
todo := initInfo()
todo[name] = input("请输入任务名称:")
todo[startTime] = input("请输入任务开始时间:")
todo[user] = input("请输入创建人:")
todos = append(todos, todo)
}
//2.任务的查询
func printInfo(todo map[string]string) {
fmt.Println(strings.Repeat("-", 20))
fmt.Println("任务id:", todo[id])
fmt.Println("任务名:", todo[name])
fmt.Println("任务状态:", todo[status])
fmt.Println(strings.Repeat("-", 20))
}
func getInfo() {
text := input("请输入查询条件:")
if text == "all" {
fmt.Println(todos)
}
for _, todo := range todos {
if strings.Contains(todo[name], text) {
printInfo(todo)
}
}
}
//3.任务的修改
func modifyInfo() {
text := input("请输入需要修改的任务名:")
for _, todo := range todos {
if strings.EqualFold(todo[name], text) {
todo[name] = input("请输入新的任务名称:")
todo[startTime] = input("请输入新的任务开始时间:")
todo[status] = statusModify
todo[user] = input("请输入新的操作人:")
fmt.Println(todo)
}
}
}
//4.任务的删除
func deleteInfo() {
text := input("请输入需要删除的任务名:")
for index, todo := range todos {
if strings.EqualFold(todo[name], text) {
//...语法糖不定长参数,会将map中的element一个个append
todos = append(todos[:index], todos[index+1:]...)
fmt.Println("删除成功")
}
}
}
func main() {
//func也是变量
methods := map[string]func(){
"add": addInfo,
"query": getInfo,
"modify": modifyInfo,
"delete": deleteInfo,
}
for {
text := input("请输入参数add/query(all)/modify/delete/exit:")
if text == "exit" {
break
}
method := methods[text]
method()
}
}