التحقق من المخزون
جزء من قسم Logic & Flow في رحلة GO على Coddy — الدرس 46 من 68.
التحدي
سهلقم بتنفيذ وظيفة فحص المخزون لنظام إدارة المخزون الخاص بك والتي تسترجع كميات المنتجات بأمان وتتعامل مع الحالات التي لا توجد فيها المنتجات. يعتمد هذا التحدي على أساس المخزون من الدرس السابق ويضيف معالجة الأخطاء لاستعلامات المخزون.
ستتلقى مدخلين:
- سلسلة نصية تحتوي على بيانات المخزون الحالي بالتنسيق
"product1:price1:quantity1,product2:price2:quantity2,product3:price3:quantity3"(على سبيل المثال،"Laptop:999.99:5,Mouse:25.50:15,Keyboard:75.00:8") - سلسلة نصية تحتوي على طلبات فحص المخزون بالتنسيق
"product1,product2,product3"(على سبيل المثال،"Mouse,Tablet,Keyboard")
مهمتك هي:
- استخدم نفس الـ
Productstruct من الدرس السابق مع حقولPrice(float64) وQuantity(int) - قم بتحليل المدخل الأول عن طريق التقسيم عند الفواصل للحصول على إدخالات المنتجات الفردية
- لكل إدخال منتج، قم بالتقسيم عند النقطتين الرأسيتين للحصول على اسم المنتج، والسعر، والكمية
- قم بتحويل سلسلة السعر النصية إلى float64 وسلسلة الكمية النصية إلى int
- قم بإنشاء وتعبئة خريطة
inventoryببيانات المنتج التي تم تحليلها - قم بإنشاء وظيفة تسمى
checkStockتأخذ خريطة المخزون واسم المنتج كمعلمات وترجع (int, error):- إذا كان المنتج موجوداً في المخزون، فقم بإرجاع كميته و nil
- إذا لم يكن المنتج موجوداً، فقم بإرجاع 0 وخطأ مع الرسالة
"product not found: [product_name]"
- قم بتحليل المدخل الثاني عن طريق التقسيم عند الفواصل للحصول على قائمة المنتجات المراد فحصها
- اعرض عنوان فحص المخزون:
"Stock Check Results:" - لكل منتج في قائمة الفحص، استدعِ وظيفة
checkStockواعرض النتائج:- في حالة عدم وجود خطأ:
"[product_name]: [quantity] units in stock" - في حالة وجود خطأ:
"[product_name]: Error - [error_message]"
- في حالة عدم وجود خطأ:
- قم بعدّ وعرض إحصائيات الملخص:
"Check Summary:""Products checked: [total_number_of_products_checked]""Products found: [number_of_products_that_exist]""Products not found: [number_of_products_that_dont_exist]"
- اعرض إجمالي المخزون للمنتجات التي تم العثور عليها:
"Total stock for found products: [sum_of_quantities_for_existing_products] units"
- أدرج أي منتجات مفقودة:
- إذا كانت هناك منتجات مفقودة:
"Missing products: [comma_separated_list_of_missing_products]" - إذا لم تكن هناك منتجات مفقودة:
"All requested products are available"
- إذا كانت هناك منتجات مفقودة:
استخدم حزمة strings لتقسيم السلاسل النصية للمدخلات، وحزمة strconv لتحويل السلاسل النصية إلى أرقام، وحزمة errors لإنشاء رسائل الخطأ، وحزمة fmt للإخراج المنسق. يوضح هذا التحدي كيفية تنفيذ استرجاع البيانات الآمن مع معالجة الأخطاء بشكل صحيح، وهو نمط أساسي في أنظمة إدارة المخزون.
جرّب بنفسك
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
)
// Define the Product struct
type Product struct {
Price float64
Quantity int
}
func main() {
// Read input using bufio.Scanner to handle spaces properly
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
storeInfo := scanner.Text()
scanner.Scan()
productData := scanner.Text()
// 1. Parse store information (split by comma)
storeInfoParts := strings.Split(storeInfo, ",")
storeName := ""
location := ""
if len(storeInfoParts) >= 2 {
storeName = storeInfoParts[0]
location = storeInfoParts[1]
}
// 2. Parse product data (split by comma, then by colon for each product)
productEntries := strings.Split(productData, ",")
// 3. Create inventory map
inventory := make(map[string]Product)
// 4. Convert strings to appropriate types and populate inventory
for _, entry := range productEntries {
parts := strings.Split(entry, ":")
if len(parts) >= 3 {
productName := parts[0]
price, _ := strconv.ParseFloat(parts[1], 64)
quantity, _ := strconv.Atoi(parts[2])
inventory[productName] = Product{
Price: price,
Quantity: quantity,
}
}
}
// 5. Display store information
fmt.Printf("=== %s Inventory System ===\n", storeName)
fmt.Printf("Location: %s\n", location)
fmt.Printf("Inventory initialized with %d products\n", len(inventory))
// 6. Display current inventory (sorted alphabetically)
fmt.Println("Current Inventory:")
var productNames []string
for name := range inventory {
productNames = append(productNames, name)
}
sort.Strings(productNames)
for _, name := range productNames {
product := inventory[name]
fmt.Printf("- %s: $%.2f (Stock: %d)\n", name, product.Price, product.Quantity)
}
// 7. Calculate and display inventory statistics
totalProducts := len(inventory)
totalItems := 0
totalValue := 0.0
for _, product := range inventory {
totalItems += product.Quantity
totalValue += product.Price * float64(product.Quantity)
}
fmt.Println("Inventory Statistics:")
fmt.Printf("Total Products: %d\n", totalProducts)
fmt.Printf("Total Items in Stock: %d\n", totalItems)
fmt.Printf("Total Inventory Value: $%.2f\n", totalValue)
// 8. Display system status
fmt.Println("System Status: Ready")
fmt.Println("Inventory management system initialized successfully")
}جميع دروس Logic & Flow
1تدفق التحكم المتقدم
جملة Switch مع `fallthrough`الخروج من الحلقات المتداخلةالاستمرار في حلقة محددةجملة `goto`ملخص - التحكم المتقدم في الحلقات2الـ Structs والميثودز (Methods)
تعريف الـ Methods على الـ Structsالـ Value Receiversالـ Pointer Receiversاختيار الـ Receiversالـ Methods مقابل الـ Functionsملخص - سلوك الـ Struct5تعمق في الـ Maps
Maps من نوع Structsالـ Pointers كقيم في الـ Mapsالتحقق من الـ Nil Mapsمقارنة الـ Mapsمراجعة - عداد تكرار الكلمات8مشروع: مخزون بسيط
نظرة عامة على المشروعالتحقق من المخزون3الواجهات (الأساسيات)
ما هي الواجهة؟تعريف الواجهةتطبيق الواجهةاستخدام أنواع الواجهاتالواجهة الفارغةتأكيدات النوع (Type Assertions)تبديل النوع (Type Switch)ملخص - الأشكال والسلوكيات