答案:用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) </font>
围绕库存管理,我们需要几个核心功能:
立即学习“go语言免费学习笔记(深入)”;
示例函数:
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
}
}
<p>func RemoveProduct(id string) bool {
if _, exists := inventory[id]; exists {
delete(inventory, id)
return true
}
return false
}</p><p>func GetProduct(id string) (Product, bool) {
p, exists := inventory[id]
return p, exists
}</p><p>func GetStats() (totalItems int, totalValue float64) {
for _, p := range inventory {
totalItems += p.Count
totalValue += float64(p.Count) * p.Price
}
return
}</p>可以用命令行实现基本交互,让用户输入指令:
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("简易库存系统(输入 help 查看帮助)")
<pre class='brush:php;toolbar:false;'>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 查看帮助")
}
}}
这个项目可以逐步增强:
基本上就这些。不复杂但能跑通流程,适合练手。
以上就是Golang如何构建简单的库存统计项目的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号