Asking for best practices

I’m on Stage #IZ3.

I passed the stage but I don’t think I’m doing it with best pracices.

And here’s a snippet of my code:

package main

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

func main() {
	for {
		fmt.Fprint(os.Stdout, "$ ")
		input, err := bufio.NewReader(os.Stdin).ReadString('\n')
		if err != nil {
			fmt.Fprint(os.Stderr, "ERROR: ", err)
			return
		}
		input = strings.TrimSpace(input) // to remove the \n
		if input == "exit 0" {
			return
		}
		words := strings.Fields(input)
		if words[0] == "echo" {
			for i := 1; i < len(words); i++ {
				fmt.Fprint(os.Stdout, words[i]+" ")
			}
			fmt.Fprint(os.Stdout, "\n")
		} else {
			fmt.Fprint(os.Stdout, input+": command not found\n")
		}
	}
}

am I doing well or there’s a better way?

Hi @mennatawfiq, you’re off to a solid start. Your implementation is clear and functional, which is great!

That said, there are a few ways to improve readability and align better with best practices:

  1. Separate logic into functions

Instead of having all the logic in the main() function, consider breaking it down into smaller functions.

For example:

  • A function to parse the input.
  • A function to execute the parsed command.
  1. Use switch for command handling

Using switch instead of if-else makes it easier to add more commands later.


You’re doing a great job so far!