以下是一个相对复杂的 Go 语言代码示例,用于实现一个简单的在线购物平台:
代码语言:javascript复制package main
import (
"fmt"
)
type User struct {
ID int
Name string
Email string
Password string
Address string
}
type Product struct {
ID int
Name string
Price float64
}
type CartItem struct {
Product Product
Quantity int
}
type Order struct {
ID int
User User
TotalPrice float64
Items []CartItem
}
type ShoppingPlatform struct {
Users map[int]User
Products map[int]Product
Orders map[int]Order
}
func main() {
shoppingPlatform := ShoppingPlatform{
Users: make(map[int]User),
Products: make(map[int]Product),
Orders: make(map[int]Order),
}
// 添加一些用户
shoppingPlatform.addUser(User{
ID: 1,
Name: "John Smith",
Email: "john@example.com",
Password: "password",
Address: "123 Main St",
})
shoppingPlatform.addUser(User{
ID: 2,
Name: "Jane Doe",
Email: "jane@example.com",
Password: "password",
Address: "456 Elm St",
})
// 添加一些产品
shoppingPlatform.addProduct(Product{
ID: 1,
Name: "iPhone 13",
Price: 999.99,
})
shoppingPlatform.addProduct(Product{
ID: 2,
Name: "Samsung Galaxy S21",
Price: 899.99,
})
// 创建一个购物车
cart := shoppingPlatform.createCart()
// 向购物车中添加产品
cart.addProduct(shoppingPlatform.Products[1], 2)
cart.addProduct(shoppingPlatform.Products[2], 1)
// 提交订单
order := cart.checkout(shoppingPlatform.Users[1])
shoppingPlatform.addOrder(order)
// 显示用户的订单
fmt.Printf("%s 的订单:n", order.User.Name)
for _, item := range order.Items {
fmt.Printf("%s - 数量: %d, 单价: %.2f, 小计: %.2fn", item.Product.Name, item.Quantity, item.Product.Price, item.Quantity*item.Product.Price)
}
fmt.Printf("总价格: %.2fn", order.TotalPrice)
}
func (sp *ShoppingPlatform) addUser(user User) {
sp.Users[user.ID] = user
}
func (sp *ShoppingPlatform) addProduct(product Product) {
sp.Products[product.ID] = product
}
func (sp *ShoppingPlatform) createCart() Cart {
return Cart{}
}
func (sp *ShoppingPlatform) addOrder(order Order) {
sp.Orders[order.ID] = order
}
func (c *Cart) addProduct(product Product, quantity int) {
item := CartItem{
Product: product,
Quantity: quantity,
}
c.Items = append(c.Items, item)
}
func (c *Cart) checkout(user User) Order {
var totalPrice float64
for _, item := range c.Items {
totalPrice = item.Product.Price * float64(item.Quantity)
}
order := Order{
ID: len(shoppingPlatform.Orders) 1,
User: user,
TotalPrice: totalPrice,
Items: c.Items,
}
c.Items = []CartItem{} // 清空购物车
return order
}
这个代码示例实现了一个简单的在线购物平台,包括用户、产品、购物车和订单的结构体,以及添加用户、产品、创建购物车、添加产品到购物车、提交订单和显示订单的方法。示例中展示了用户在购物平台上选购产品、添加到购物车、提交订单,并打印出订单的详情。希望这个示例能够对您提供一些参考!如果您还有其他问题,请随时提问。