Skip to content

Instantly share code, notes, and snippets.

@quaintdev
Created January 11, 2023 14:14
Show Gist options
  • Save quaintdev/5dcf2753a1a538e5aa0acea776dda1df to your computer and use it in GitHub Desktop.
Save quaintdev/5dcf2753a1a538e5aa0acea776dda1df to your computer and use it in GitHub Desktop.
Sample Go programming assignment involving structs and composition:

Create a program that models a shopping cart for a e-commerce website. The program should include the following structs:

  • Item struct, with fields for the item's name, price, and quantity.
  • Cart struct, with a field for a slice of Item structs and methods for adding an item to the cart, removing an item from the cart, and calculating the total cost of the items in the cart.

Your program should allow a user to create a new cart, add items to the cart, remove items from the cart, and display the total cost of the items in the cart.

Here is a skeleton of the code

package main

type Item struct {
    name  string
    price float64
    quantity int
}

type Cart struct {
    items []Item
}

func (c *Cart) AddItem(i Item) {
    // Add code here to add an item to the cart
}

func (c *Cart) RemoveItem(name string) {
    // Add code here to remove an item from the cart
}

func (c *Cart) TotalCost() float64 {
    // Add code here to calculate the total cost of the items in the cart
}

func main() {
    // Create a new cart
    cart := Cart{}
    // Add items to the cart
    cart.AddItem(Item{name: "item1", price: 10.0, quantity: 1})
    cart.AddItem(Item{name: "item2", price: 20.0, quantity: 2})
    // Remove an item from the cart
    cart.RemoveItem("item1")
    // Display the total cost of the items in the cart
    fmt.Println("Total cost: ", cart.TotalCost())
}

This is just a skeleton code, you need to write the logic for the AddItem, RemoveItem and TotalCost function.

This Assignment will check your understanding of creating struct, composing them and using pointer receivers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment