Golang

 

Introduction

The Book Inventory System is a simple yet effective way to manage a bookstore’s inventory. In this project, we will use the Go programming language to build a basic system that allows for creating, viewing, updating, and deleting books in the inventory. The system will help bookshop owners keep track of their stock efficiently.

Objective

The objective of this project is to create a command-line application where a user can perform basic CRUD (Create, Read, Update, Delete) operations on a book inventory. The application will allow the addition of books with details like title, author, and price, as well as update and delete books from the inventory.

Code Implementation in Go

package main

import (
    "fmt"
    "os"
)

type Book struct {
    ID     int
    Title  string
    Author string
    Price  float64
}

var inventory []Book
var nextID = 1

func main() {
    for {
        fmt.Println("\nBook Inventory System")
        fmt.Println("1. Add Book")
        fmt.Println("2. View Books")
        fmt.Println("3. Update Book")
        fmt.Println("4. Delete Book")
        fmt.Println("5. Exit")
        fmt.Print("Choose an option: ")

        var choice int
        _, err := fmt.Scanf("%d", &choice)
        if err != nil {
            fmt.Println("Invalid choice, please enter a valid option.")
            continue
        }

        switch choice {
        case 1:
            addBook()
        case 2:
            viewBooks()
        case 3:
            updateBook()
        case 4:
            deleteBook()
        case 5:
            fmt.Println("Exiting the program...")
            os.Exit(0)
        default:
            fmt.Println("Invalid choice. Please try again.")
        }
    }
}

func addBook() {
    var title, author string
    var price float64

    fmt.Print("Enter Book Title: ")
    fmt.Scanf("%s", &title)
    fmt.Print("Enter Author Name: ")
    fmt.Scanf("%s", &author)
    fmt.Print("Enter Book Price: ")
    fmt.Scanf("%f", &price)

    newBook := Book{
        ID:     nextID,
        Title:  title,
        Author: author,
        Price:  price,
    }

    inventory = append(inventory, newBook)
    nextID++

    fmt.Println("Book added successfully!")
}

func viewBooks() {
    if len(inventory) == 0 {
        fmt.Println("No books available in the inventory.")
        return
    }

    fmt.Println("\nBooks in Inventory:")
    for _, book := range inventory {
        fmt.Printf("ID: %d | Title: %s | Author: %s | Price: $%.2f\n", book.ID, book.Title, book.Author, book.Price)
    }
}

func updateBook() {
    var id int
    fmt.Print("Enter Book ID to update: ")
    fmt.Scanf("%d", &id)

    var found bool
    for i, book := range inventory {
        if book.ID == id {
            var title, author string
            var price float64

            fmt.Print("Enter new Title: ")
            fmt.Scanf("%s", &title)
            fmt.Print("Enter new Author: ")
            fmt.Scanf("%s", &author)
            fmt.Print("Enter new Price: ")
            fmt.Scanf("%f", &price)

            inventory[i] = Book{
                ID:     book.ID,
                Title:  title,
                Author: author,
                Price:  price,
            }

            fmt.Println("Book updated successfully!")
            found = true
            break
        }
    }

    if !found {
        fmt.Println("Book with the given ID not found.")
    }
}

func deleteBook() {
    var id int
    fmt.Print("Enter Book ID to delete: ")
    fmt.Scanf("%d", &id)

    var found bool
    for i, book := range inventory {
        if book.ID == id {
            inventory = append(inventory[:i], inventory[i+1:]...)
            fmt.Println("Book deleted successfully!")
            found = true
            break
        }
    }

    if !found {
        fmt.Println("Book with the given ID not found.")
    }
}

Explanation of the Program

This Book Inventory System allows users to perform CRUD operations on a list of books. Let’s break down the program structure:

Program Structure

  • Book struct: Defines the structure of a book, with fields for ID, title, author, and price.
  • Inventory: A slice of books used to store the list of books in the system.
  • Main loop: The main function contains a loop that keeps running, presenting a menu to the user for performing operations. The loop continues until the user chooses to exit.
  • CRUD Functions:
    • addBook(): Prompts the user for book details and adds the book to the inventory.
    • viewBooks(): Displays all the books currently in the inventory.
    • updateBook(): Allows the user to update a book’s details by entering the book ID.
    • deleteBook(): Deletes a book from the inventory using its ID.

How to Run the Program

  1. Ensure that you have Go installed on your system. If not, download and install it from here.
  2. Save the Go code into a file named inventory.go.
  3. Open the terminal and navigate to the directory where the inventory.go file is located.
  4. Run the program by typing the command: go run inventory.go.
  5. Follow the on-screen instructions to add, view, update, or delete books from the inventory.
© 2025 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 :)