答案:用Golang构建库存系统需定义商品结构体和map存储,实现增删改查及统计功能,并通过命令行交互。1. 定义Product结构体含ID、Name、Count、Price;2. 使用map[string]Product以ID为键存储;3. 实现AddProduct合并同ID商品数量;4. RemoveProduct按ID删除并返回布尔值;5. GetProduct查询商品存在性;6. GetStats计算总数量与总价值;7. main函数中用scanner接收用户输入,支持add、get、stats、help、exit命令;8. 扩展可加文件持久化、价格输入、API服务等。该设计简洁实用,适合学习与小型应用。

用Golang构建一个简单的库存统计项目,关键在于设计清晰的数据结构、实现基础的增删改查功能,并提供简单的交互方式。下面是一个轻量级但实用的实现思路,适合学习或小型应用。
定义库存数据结构
库存的核心是商品信息。我们可以用一个结构体来表示商品:
type Product struct {
ID string // 商品编号
Name string // 商品名称
Count int // 库存数量
Price float64 // 单价
}
使用map来存储商品,以ID为键,便于快速查找:
var inventory = make(map[string]Product)
实现基础操作函数
围绕库存管理,我们需要几个核心功能:
立即学习“go语言免费学习笔记(深入)”;
- 添加商品:向库存中加入新商品或更新已有商品数量
- 删除商品:根据ID移除商品
- 查询商品:按ID查看商品详情
- 统计总库存和总价值:计算所有商品的数量与总价
示例函数:
func AddProduct(p Product) {
if existing, exists := inventory[p.ID]; exists {
inventory[p.ID] = Product{
ID: p.ID,
Name: existing.Name,
Count: existing.Count + p.Count,
Price: p.Price,
}
} else {
inventory[p.ID] = p
}
}
func RemoveProduct(id string) bool {
if _, exists := inventory[id]; exists {
delete(inventory, id)
return true
}
return false
}
func GetProduct(id string) (Product, bool) {
p, exists := inventory[id]
return p, exists
}
func GetStats() (totalItems int, totalValue float64) {
for _, p := range inventory {
totalItems += p.Count
totalValue += float64(p.Count) * p.Price
}
return
}
提供简单交互界面
可以用命令行实现基本交互,让用户输入指令:
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("简易库存系统(输入 help 查看帮助)")
for {
fmt.Print("> ")
scanner.Scan()
text := strings.TrimSpace(scanner.Text())
parts := strings.Split(text, " ")
switch parts[0] {
case "add":
if len(parts) == 4 {
id, name := parts[1], parts[2]
count, _ := strconv.Atoi(parts[3])
AddProduct(Product{ID: id, Name: name, Count: count, Price: 1.0})
fmt.Println("已添加/更新商品")
} else {
fmt.Println("用法: add [id] [name] [count]")
}
case "get":
if len(parts) == 2 {
if p, ok := GetProduct(parts[1]); ok {
fmt.Printf("ID: %s, 名称: %s, 数量: %d, 单价: %.2f\n", p.ID, p.Name, p.Count, p.Price)
} else {
fmt.Println("商品不存在")
}
}
case "stats":
items, value := GetStats()
fmt.Printf("总库存数量: %d, 总价值: %.2f\n", items, value)
case "help":
fmt.Println("支持命令: add, get, stats, exit")
case "exit":
return
default:
fmt.Println("未知命令,输入 help 查看帮助")
}
}}
扩展建议
这个项目可以逐步增强:
- 将数据保存到JSON或CSV文件中,重启后不丢失
- 增加单价输入,完善价格管理
- 使用flag或cobra库支持命令行参数
- 改成HTTP服务,通过API调用管理库存
基本上就这些。不复杂但能跑通流程,适合练手。










