Golang
Golang

 

 

Introduction

Managing a shopping list is a common daily task, and creating an application for this can help users organize their purchases efficiently. This program demonstrates how to build a shopping list application using Go (Golang). The application allows users to add items, view the list, and delete items, showcasing basic Go programming concepts.

Objective

The objective of this program is to create a simple command-line shopping list application in Go. The application will:

  • Add items to the shopping list
  • Display the current shopping list
  • Delete items from the list

This program serves as an introduction to Go programming for beginners and demonstrates key concepts like slices, loops, and user input handling.

Code

        package main

        import (
            "bufio"
            "fmt"
            "os"
            "strings"
        )

        func main() {
            shoppingList := []string{}
            reader := bufio.NewReader(os.Stdin)

            for {
                fmt.Println("\nShopping List Application")
                fmt.Println("1. Add item")
                fmt.Println("2. View list")
                fmt.Println("3. Delete item")
                fmt.Println("4. Exit")
                fmt.Print("Enter your choice: ")

                choice, _ := reader.ReadString('\n')
                choice = strings.TrimSpace(choice)

                switch choice {
                case "1":
                    fmt.Print("Enter item to add: ")
                    item, _ := reader.ReadString('\n')
                    item = strings.TrimSpace(item)
                    shoppingList = append(shoppingList, item)
                    fmt.Println("Item added successfully!")

                case "2":
                    fmt.Println("\nCurrent Shopping List:")
                    if len(shoppingList) == 0 {
                        fmt.Println("The shopping list is empty.")
                    } else {
                        for i, item := range shoppingList {
                            fmt.Printf("%d. %s\n", i+1, item)
                        }
                    }

                case "3":
                    fmt.Println("\nCurrent Shopping List:")
                    if len(shoppingList) == 0 {
                        fmt.Println("The shopping list is empty.")
                        break
                    }
                    for i, item := range shoppingList {
                        fmt.Printf("%d. %s\n", i+1, item)
                    }
                    fmt.Print("Enter the number of the item to delete: ")
                    var index int
                    _, err := fmt.Scan(&index)
                    if err != nil || index < 1 || index > len(shoppingList) {
                        fmt.Println("Invalid input. Please try again.")
                    } else {
                        shoppingList = append(shoppingList[:index-1], shoppingList[index:]...)
                        fmt.Println("Item deleted successfully!")
                    }

                case "4":
                    fmt.Println("Exiting the application. Goodbye!")
                    return

                default:
                    fmt.Println("Invalid choice. Please enter a valid option.")
                }
            }
        }

Explanation

The program structure is as follows:

  1. Initialize shopping list: A slice is used to store the shopping list items dynamically.
  2. Display menu options: A menu with four options is displayed in a loop until the user chooses to exit.
  3. Handle user input: User input is read using bufio.NewReader and processed based on their choice.
  4. Add items: Items entered by the user are added to the slice.
  5. View list: The program iterates over the slice to display all items.
  6. Delete items: The user specifies the index of the item to delete, and the program updates the slice accordingly.
  7. Exit: The program terminates when the user selects the exit option.

How to Run

  1. Install Go from the official Go website.
  2. Copy the code into a file named shopping_list.go.
  3. Run the program using the command:
                    go run shopping_list.go
    
  4. Follow the on-screen instructions to add, view, or delete items from the shopping list.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)