package main
import (
"fmt"
"os"
)
// 使用函数实现一个简单的图书管理系统
// 每本书有书名, 作者, 价格, 备注
// 用户可以在控制台添加, 修改书籍信息, 打印所有书籍列表
type book struct {
title string
author string
price string
}
func newBook(title, author, price string) *book {
return &book{
title: title,
author: author,
price: price,
}
}
// 创建一个切片用于存放所有书籍的指针
var allBook = make([]*book, 0, 10)
func showMenu() {
menu := `
1. 添加书籍
2. 修改书籍信息
3. 展示所有书籍
4. 退出
`
fmt.Println(menu)
}
func getInput() (string, string, string) {
// 获取用户输入, title, author, price
var (
title string
author string
price string
)
fmt.Print("请输入 title: ")
fmt.Scanln(&title)
fmt.Print("请输入 author: ")
fmt.Scanln(&author)
fmt.Print("请输入 price: ")
fmt.Scanln(&price)
return title, author, price
}
func addBook() {
// 捕获输入
title, author, price := getInput()
// 创建新书
b := newBook(title, author, price)
// 判断切片中的书是否与先加入的书重复
for _, v := range allBook {
if b.title == v.title {
return
}
}
allBook = append(allBook, b)
fmt.Println(" === 添加成功 ===")
}
func editBook() {
title, author, price := getInput()
for _, v := range allBook {
if v.title == title {
v.author = author
v.price = price
fmt.Println(" === 修改成功 ===")
return
}
}
fmt.Println("书籍不存在")
}
func showBook() {
for _, v := range allBook {
fmt.Println(*v)
}
}
func main() {
for {
// 打印菜单
showMenu()
var input int
// 等待用户输入菜单选项
fmt.Scan(&input)
switch input {
// 添加
case 1:
addBook()
// 修改
case 2:
editBook()
// 展示
case 3:
showBook()
// 退出
case 4:
os.Exit(0)
}
}
}