package main
import (
“fmt”
“os”
)
//1.定义结构体
//2.打印菜单
//3.等待用户输入
//4.添加书籍函数
//5.修改书籍函数
//6.展示书籍函数
//7.退出 os.Exit(0)
//1.定义结构体
type book struct {
title string
author string
price float32
xinxi bool
}
//定义创建新书的构造函数
func newbook(title, author string, price float32, xinxi bool) *book {
return &book{
title: title,
author: author,
price: price,
xinxi: xinxi,
}
}
//定义book指针切片 存储所有书籍
var allbook = make([]*book,0,200)
//2.打印菜单
func caidan() {
fmt.Println(“欢迎登陆书籍管理系统”)
fmt.Println(“1.添加书籍”)
fmt.Println(“2.修改书籍信息”)
fmt.Println(“3.展示所有书籍”)
fmt.Println(“4.退出”)
fmt.Println(“请选择:”)
}
func userprint() *book {
var (
title string
author string
price float32
xinxi bool
)
fmt.Println(“根据提示输入内容”)
fmt.Print(“请输入书名:”)
fmt.Scanln(&title)
fmt.Print(“请输入作者:”)
fmt.Scanln(&author)
fmt.Print(“请输入价格:”)
fmt.Scanln(&price)
fmt.Print(“是否上架:[true][false]”)
fmt.Scanln(&xinxi)
fmt.Println(title,author,price,xinxi)
book := newbook(title,author,price,xinxi)
return book
}
//4.添加书籍函数
func addBook() {
//4.1 获取用户输入
//4.2 创建新书
book := userprint()
//4.3 将书添加到allbook切片
//4.3.1判断新增的书是否已经存在
for _,b :=range allbook {
if b.title == book.title {
fmt.Printf(“这本书已经存在%s”,book.title)
return
}
}
allbook = append(allbook,book)
fmt.Println(“添加书籍成功”)
}
//5.修改书籍函数
func updateBooK() {
book := userprint()
//5.1遍历所有书籍根据书名找到要修改的书籍 把信息更新一下
for index , b := range allbook {
if b.title == book.title {
allbook[index] = book
fmt.Printf(“书名:%s 更新成功”,book.title)
return
}
}
fmt.Printf(“%s无任何信息”,book.title)
}
//6.展示书籍函数
func showBooK() {
if len(allbook) == 0 {
fmt.Println(“无任何信息”)
return
}
for _,b :=range allbook {
fmt.Printf(“%s 作者:%s 价格:%2.f 是否上架:%t\n “,b.title,b.author,b.price,b.xinxi)
}
}
func main() {
for {
caidan()
//等待用户输入菜单选项
var option int
fmt.Scanln(&option)
switch option {
case 1:
addBook()
case 2:
updateBooK()
case 3:
showBooK()
case 4:
os.Exit(0)
}
}
}