首頁  >  文章  >  後端開發  >  如何使用Go語言實作一個下單系統

如何使用Go語言實作一個下單系統

PHPz
PHPz原創
2023-04-05 13:48:34980瀏覽

本文將介紹如何使用Go語言實作一個簡單易懂的下單系統。

一、需求分析

我們需要一個簡單易懂的下單系統,至少需要實作以下幾個功能:

  1. 商品的展示與選擇
  2. 購物車的功能
  3. 訂單的生成與顯示

考慮到我們的時間和精力有限,我們將只實現一個簡單的商城系統,而我們只提供兩個商品可供選擇。這兩個商品的資訊如下:

商品名稱 商品價格
商品1 10元
商品2 #20元

我們需要在命令列中實現這個商城系統。

二、程式碼實作

  1. 建立商品結構體

#我們首先需要建立一個結構體來儲存商品訊息,程式碼範例如下:

type product struct {
    name  string
    price int
}

var products = []product{
    {"商品1", 10},
    {"商品2", 20},
}
  1. 商品展示

我們需要實作一個函數來展示商品訊息,程式碼範例如下:

func showProducts() {
    fmt.Println("== 商品列表 ==")
    for _, p := range products {
        fmt.Printf("%s %d元\n", p.name, p.price)
    }
    fmt.Println("================")
}
  1. 購物車實作

我們需要實作一個購物車結構體來儲存使用者選擇的商品訊息,程式碼範例如下:

type cart struct {
    items map[string]int
}

func newCart() *cart {
    return &cart{items: make(map[string]int)}
}

func (c *cart) addItem(name string, qty int) {
    c.items[name] += qty
}

func (c *cart) clear() {
    c.items = make(map[string]int)
}

func (c *cart) total() int {
    total := 0
    for name, qty := range c.items {
        for _, p := range products {
            if p.name == name {
                total += p.price * qty
                break
            }
        }
    }
    return total
}

func (c *cart) show() {
    if len(c.items) == 0 {
        fmt.Println("购物车为空")
        return
    }

    fmt.Println("== 购物车 ==")
    for name, qty := range c.items {
        fmt.Printf("%s × %d\n", name, qty)
    }
    fmt.Printf("总计 %d元\n", c.total())
    fmt.Println("============")
}
  1. 下單實作

我們需要實現一個下單函數,即將購物車中的商品資訊產生為訂單,程式碼範例如下:

func checkout(c *cart) {
    if len(c.items) == 0 {
        fmt.Println("购物车为空")
        return
    }

    // 生成订单
    order := make(map[string]int)
    for name, qty := range c.items {
        order[name] = qty
    }

    // 清空购物车
    c.clear()

    fmt.Println("== 订单详情 ==")
    for name, qty := range order {
        for _, p := range products {
            if p.name == name {
                fmt.Printf("%s × %d\n", name, qty)
                fmt.Printf("单价 %d元,总价 %d元\n", p.price, p.price*qty)
                break
            }
        }
    }
    fmt.Printf("总计 %d元\n", c.total())
    fmt.Println("============")
}
  1. #命令列互動

我們需要實作一個命令列互動函數,供使用者選擇商品及數量,並完成下單,程式碼範例如下:

func interactive() {
    scanner := bufio.NewScanner(os.Stdin)
    c := newCart()

    for {
        showProducts()
        c.show()
        fmt.Print("请选择商品(输入商品编号):")
        scanner.Scan()
        id := scanner.Text()
        if id == "q" {
            break
        }

        var p product
        for _, p = range products {
            if p.name == id {
                break
            }
        }
        if p.price == 0 {
            fmt.Printf("商品 %s 不存在\n", id)
            continue
        }

        fmt.Print("请输入数量:")
        scanner.Scan()
        qtyStr := scanner.Text()
        qty, err := strconv.Atoi(qtyStr)
        if err != nil {
            fmt.Println("输入的数量无效")
            continue
        }

        c.addItem(p.name, qty)
    }

    checkout(c)
}

三、完整程式碼

完整程式碼如下:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
)

type product struct {
    name  string
    price int
}

var products = []product{
    {"商品1", 10},
    {"商品2", 20},
}

type cart struct {
    items map[string]int
}

func newCart() *cart {
    return &cart{items: make(map[string]int)}
}

func (c *cart) addItem(name string, qty int) {
    c.items[name] += qty
}

func (c *cart) clear() {
    c.items = make(map[string]int)
}

func (c *cart) total() int {
    total := 0
    for name, qty := range c.items {
        for _, p := range products {
            if p.name == name {
                total += p.price * qty
                break
            }
        }
    }
    return total
}

func (c *cart) show() {
    if len(c.items) == 0 {
        fmt.Println("购物车为空")
        return
    }

    fmt.Println("== 购物车 ==")
    for name, qty := range c.items {
        fmt.Printf("%s × %d\n", name, qty)
    }
    fmt.Printf("总计 %d元\n", c.total())
    fmt.Println("============")
}

func showProducts() {
    fmt.Println("== 商品列表 ==")
    for _, p := range products {
        fmt.Printf("%s %d元\n", p.name, p.price)
    }
    fmt.Println("================")
}

func checkout(c *cart) {
    if len(c.items) == 0 {
        fmt.Println("购物车为空")
        return
    }

    // 生成订单
    order := make(map[string]int)
    for name, qty := range c.items {
        order[name] = qty
    }

    // 清空购物车
    c.clear()

    fmt.Println("== 订单详情 ==")
    for name, qty := range order {
        for _, p := range products {
            if p.name == name {
                fmt.Printf("%s × %d\n", name, qty)
                fmt.Printf("单价 %d元,总价 %d元\n", p.price, p.price*qty)
                break
            }
        }
    }
    fmt.Printf("总计 %d元\n", c.total())
    fmt.Println("============")
}

func interactive() {
    scanner := bufio.NewScanner(os.Stdin)
    c := newCart()

    for {
        showProducts()
        c.show()
        fmt.Print("请选择商品(输入商品编号):")
        scanner.Scan()
        id := scanner.Text()
        if id == "q" {
            break
        }

        var p product
        for _, p = range products {
            if p.name == id {
                break
            }
        }
        if p.price == 0 {
            fmt.Printf("商品 %s 不存在\n", id)
            continue
        }

        fmt.Print("请输入数量:")
        scanner.Scan()
        qtyStr := scanner.Text()
        qty, err := strconv.Atoi(qtyStr)
        if err != nil {
            fmt.Println("输入的数量无效")
            continue
        }

        c.addItem(p.name, qty)
    }

    checkout(c)
}

func main() {
    interactive()
}

四、總結

本文簡單介紹如何使用Go語言實現一個簡單易懂的下單系統,透過實現商品展示、購物車功能和訂單生成與顯示等功能,我們實現了一個有用的商城系統,具有一定的實用性和參考價值。在開發前,我們需要充分了解需求及目標,以便能夠更好的完成產品開發,同時,Go語言的高效性和簡潔性也為我們提供了可靠和高效的開發工具和支援。

以上是如何使用Go語言實作一個下單系統的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn