Skip to content

Instantly share code, notes, and snippets.

@aldy505
Created November 25, 2021 14:05
Show Gist options
  • Save aldy505/5023e0dd36f379d730750d8eeebbdfcf to your computer and use it in GitHub Desktop.
Save aldy505/5023e0dd36f379d730750d8eeebbdfcf to your computer and use it in GitHub Desktop.
Simple coffee shop to learn about Golang structs & methods
// This is a coffee shop.
// We can order coffee and see the menu.
//
// The problem is that this coffee shop
// code is not complete yet.
//
// This is just to train your skills on
// dealing with structs, variables,
// array/slices, methods, and types.
//
// Good luck!
//
// You can always google something out
// if you don't know about it!
package main
import "fmt"
type CoffeeShop struct {
Name string
Menu []Product
}
type Product struct {
Name string
Price int64
Quantity int32
}
func main() {
// Create a new coffee shop
cafe := NewCoffeeShop("Coffee Shop")
// Hmm, let me check the menu first.
menu := cafe.GetMenu()
fmt.Println(menu)
// That output above should be empty.
// Add some products to the menu
cafe.AddProduct("Cappuccino", 2, 10)
cafe.AddProduct("Latte", 3, 10)
cafe.AddProduct("Espresso", 1, 20)
cafe.AddProduct("Americano", 2, 10)
// Hey, I want to see the menu!
menu := cafe.GetMenu()
fmt.Println(menu)
// Menu above should consist of Cappuccino, Latte, Espresso, and Americano
// OK, I've seen the menu.
// I want to order one cup of cappuccino!
cafe.Order("Cappuccino", 1)
// Let me see the menu again
menu = cafe.GetMenu()
fmt.Println(menu)
// By now, the cappuccino quantity should be decreased by one
// Oh, hey! Another customer.
// I want to order 2 cup of latte and 1 cup of americano, please.
cafe.Order("Americano", 1)
cafe.Order("Latte", 2)
// It's nearly closing time, let's check the menu.
menu = cafe.GetMenu()
fmt.Println(menu)
// By now, the cappucino quantity should be decreased by one
// Also the americano, and the latte should be decreased
// to 1 and 2 respectfully.
}
func NewCoffeeShop(name string) *CoffeeShop {
// Create a new coffee shop
return &CoffeeShop{
Name: name,
}
}
func (c *CoffeeShop) AddProduct(name string, price int64, quantity int32) {
// Add a product to the menu
c.Menu = append(c.Menu, Product{
Name: name,
Price: price,
Quantity: quantity,
})
}
func (c *CoffeeShop) GetMenu() []Product {
// Return the menu
// Write code here!
}
func (c *CoffeeShop) Order(name string, quantity int32) {
// Decrease the quantity of the product
// Write code here!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment