Go

CLI Development

CLI design, flag package, cobra/viper, structuring CLI apps, exit codes, stdin/stdout/stderr, UX patterns, testing CLI apps

20 interview questionsยท
Senior
1

What is the main role of the flag package in Go?

Answer

The flag package provides a simple API for parsing command-line arguments. It allows defining flags with predefined types (string, int, bool, etc.) and automatically handles parsing and validation. This package is part of the standard library and is suitable for simple CLIs.

2

How to define a string flag with the flag package and retrieve its value?

Answer

The flag.String function returns a pointer to the flag value. After calling flag.Parse(), the value can be accessed by dereferencing the pointer. It's also possible to use flag.StringVar to bind directly to an existing variable.

3

What is the difference between flag.String and flag.StringVar?

Answer

flag.String allocates a new variable and returns a pointer to it, while flag.StringVar binds the flag to an existing variable passed by address. StringVar is useful when the variable needs to be defined at package level or when you want to avoid dereferencing.

4

What exit code should be used when a CLI application encounters an invalid arguments error?

5

What is the main advantage of Cobra over the standard flag package?

+17 interview questions

Master Go for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free