package main
import("fmt""os")// 展示菜单funcshowMenu(){
menu :=`
1. 添加
2. 修改
3. 删除
4. 展示
5. 退出
`
fmt.Println(menu)}// 捕获输入的标题funcgetTitle()(title string){
fmt.Print("请输入 Title: ")
fmt.Scanln(&title)return}// 捕获输入的价格funcgetPrice()(price int){
fmt.Print("请输入 Price: ")
fmt.Scanln(&price)return}funcmain(){// 构建一个 mgr 结构体, 提供各种方法
m :=newMgr(2)// 循环, 相当于 while truefor{// 展示菜单showMenu()// 获取用户指定的选项var opt int
fmt.Print("请选择: ")
fmt.Scanln(&opt)// 根据输入执行不同的方法switch opt {// 添加书籍case1:// 捕获书籍标题
t :=getTitle()
m.addBook(t)// 修改书籍case2:
t :=getTitle()
m.editBook(t)// 删除书籍case3:
t :=getTitle()
m.delBook(t)// 展示书籍case4:
m.showBook()// 退出case5:
os.Exit(0)default:
fmt.Println("输入有误")}}}
book.go
package main
// book 书籍结构体type book struct{
title string
price int}funcnewBook(title string, price int)*book {return&book{
title: title,
price: price,}}
bookmgr.go
package main
// 这里有一个问题, 如果不是按照正确的数据类型录入就会提前结束, 未解决import"fmt"type mgr struct{
allBook []*book
}funcnewMgr(l int)*mgr {// func new结构体名 (构建结构体需要的所有元素) 结构体的指针
s :=make([]*book,0, l)return&mgr{// return &结构体
allBook: s,}}// 遍历 allBook 切片// 如果发现切片中的 title 和参数 title 相同, 则返回 true 表示书籍已存在, 并返回对应的索引// 如果没有相同, 则返回 false 表示没有相同, 返回 0 忽略不计func(m *mgr)checkBook(t string)(bool,int){for k, v :=range m.allBook {if v.title == t {returntrue, k
}}returnfalse,0}func(m *mgr)addBook(t string){
ok,_:= m.checkBook(t)if ok {
fmt.Println("书籍已经存在")}else{
p :=getPrice()
b :=newBook(t, p)
m.allBook =append(m.allBook, b)
fmt.Println("添加书籍成功")}}func(m *mgr)editBook(t string){
ok, k := m.checkBook(t)if ok {
p :=getPrice()
m.allBook[k].price = p
fmt.Println("修改完成")}else{
fmt.Println("书籍不存在")}}func(m *mgr)delBook(t string){
ok, k := m.checkBook(t)if ok {
m.allBook =append(m.allBook[:k], m.allBook[k+1:]...)
fmt.Println("删除成功")}else{
fmt.Println("书籍不存在")}}func(m *mgr)showBook(){for_, v :=range m.allBook {
fmt.Println(*v)}}
执行
# 直接执行
go run book.go main.go bookmgr.go # 无顺序要求# 编译后执行
go build # 会生成可执行文件