Improving the List Output Format

Powerful Command-Line Applications in Go — by Ricardo Gerardi (24 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Display Command-Line Tool Usage | TOC | Increasing Flexibility with Environment Variables 👉

You’ve made good progress on your to-do list tool so far, but the list output is still not very informative. At this moment, this is what you see when executing the tool with the -list option:

​ ​$ ​​./todo​​ ​​-list​
​ Another ToDo item
​ Improve usage
​ Improve output

Various ways exist for improving the output formatting. For instance, if you don’t own the API code, your only alternative is to format the output in the command-line tool implementation. But you own the API, so we can leverage the powerful Interfaces feature of Go to implement the list output formatting in the todo.List type directly. With this approach, anyone using your API experiences a consistent output format.

An interface in Go implements a contract but, unlike other languages, Go interfaces define only behavior and not state. This means that an interface defines what a type should do and not what type of data it should hold.

So, to satisfy an interface, a type needs only to implement all the methods defined in the interface with the same signature. In addition, satisfying an interface doesn’t require explicit declaration. Types will implicitly implement an interface by implementing all the defined methods.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.