package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
//创建用户
func UserCreate(user map[string]interface{}) {
//获取信息, 构建 user
users = append(users, user)
}
func UsersPrint(users []map[string]interface{}) {
fmt.Printf("%#v", users)
head := `
id name age
--+--------+--------+-----------
`
var s string
for id, user := range users {
s += fmt.Sprintf(" %v %v %v\n", id, user["name"], user["age"])
}
fmt.Println(head + s)
}
//列出所有用户
func UserList(users []map[string]interface{}) (usersRes []map[string]interface{}) {
//for _, user := range users {
// fmt.Println(user)
//}
usersRes = users
return
}
//检索用户
func UserRetrieval(id int) (user map[string]interface{}) {
if len(users) > id {
return users[id]
} else {
fmt.Println("检索失败, 用户不存在")
return nil
}
}
//更新用户(所有字段)
func UserUpdate(id int, user map[string]interface{}) {
if len(users) > id {
users[id] = user
} else {
fmt.Println("更新失败, 用户不存在")
}
}
//删除用户
func UserDestroy(id int) {
if len(users) > id {
users = append(users[:id], users[id+1:]...)
} else {
fmt.Println("删除失败, 用户不存在")
}
}
var users = []map[string]interface{}{}
func menu() (opId string) {
fmt.Println(`
0 增加用户
1 删除用户
2 更新用户
3 查询所有用户
4 查询用户
5 退出
请输入要操作码id(0/1/2/3/4/5)>>
`)
opId, _ = bufio.NewReader(os.Stdin).ReadString('\n')
opId = strings.Trim(opId, "\r\n")
return
}
func getArgs(name string) (args string) {
//var args string
for {
fmt.Printf("请输入 %s >> \n", name)
args, _ = bufio.NewReader(os.Stdin).ReadString('\n')
args = strings.Trim(args, "\r\n ")
if len(args) != 0 {
break
} else {
fmt.Printf("%s 不能为空>> \n", name)
}
}
return
}
func main() {
for {
opId := menu()
switch opId {
case "0":
//创建用户
user := map[string]interface{}{}
user["name"] = getArgs("name")
user["age"] = getArgs("age")
UserCreate(user)
usersRes := UserList(users)
UsersPrint(usersRes)
case "1":
//删除用户
userId, _ := strconv.Atoi(getArgs("id"))
UserDestroy(userId)
users := UserList(users)
UsersPrint(users)
case "2":
//更新用户
//打印用户
users := UserList(users)
UsersPrint(users)
//获取参数
userId, _ := strconv.Atoi(getArgs("id"))
//构建user
user := map[string]interface{}{}
user["name"] = getArgs("name")
user["age"] = getArgs("age")
//更新
UserUpdate(userId, user)
//打印用户
users = UserList(users)
UsersPrint(users)
case "3":
users := UserList(users)
UsersPrint(users)
case "4":
//检索用户
fmt.Println("请输入要检索用户的id >> ")
userId, _ := strconv.Atoi(getArgs("id"))
UserRetrieval(userId)
case "5":
os.Exit(0)
default:
fmt.Println("操作码输入为空或不正确, 请重新输入...")
menu()
}
}
}