Go, from zero to a running service · Chapter 3 of 12 · Languages · new chapter every Tuesday night
By the end of this chapter: Model data in a language that deliberately has no classes.
The problem
Emma is a junior backend engineer on a fintech startup that just landed its first B2B client. The client wants a new “transaction‑validation” service that will sit behind the existing Java monolith. The product manager has pushed the deadline to two weeks because the client’s contract starts next month.
Emma, eager to prove herself, decides to write the service in Go because the team’s senior engineer swore it would “just work faster”. She clones a starter repository, adds a single http.Handler that parses JSON, validates a few fields and returns a 200 OK. She runs the binary locally and everything looks fine.
However, as she starts to add more validation rules and error handling, her code becomes increasingly complex and hard to manage. She's using a mix of maps and structs to represent the transaction data, but it's getting difficult to keep track of what's what. The code is starting to look like a mess, and she's worried that she won't be able to meet the deadline. She's heard that Go has a strong focus on simplicity and readability, but she's not sure how to apply that to her code.
The problem Emma is facing is that she doesn't know how to effectively model her data in Go, and her code is suffering as a result. She needs to learn how to use Go's type system, structs, and methods to create clean, readable, and maintainable code.
Before you start
To follow along with this chapter, you should have a basic understanding of Go's syntax and have completed the previous chapter on setting up a Go project. You should also have Go 1.18 or later installed on your machine. You can verify this by running the command go version in your terminal. If you're using an earlier version of Go, you may need to upgrade before proceeding.
Understanding Go's type system
Go's type system is designed to be simple and efficient. It has a few built-in types, such as int, string, and bool, but it also allows you to create your own custom types using structs.
Defining a struct
A struct in Go is a collection of fields that can be of different types. You can define a struct using the struct keyword followed by the name of the struct and the fields it contains.
type Transaction struct { ID string Amount float64 Currency string Timestamp time.Time } In this example, we're defining a Transaction struct with four fields: ID, Amount, Currency, and Timestamp.
Creating a new struct instance
To create a new instance of a struct, you can use the struct keyword followed by the name of the struct and the values for each field.
tx := Transaction{ ID: "12345", Amount: 10.99, Currency: "USD", Timestamp: time.Now(), } Alternatively, you can use the & operator to create a pointer to a new struct instance.
tx := &Transaction{ ID: "12345", Amount: 10.99, Currency: "USD", Timestamp: time.Now(), } Adding methods to a struct
In Go, you can add methods to a struct by defining a function with a receiver parameter that is a pointer to the struct.
func (tx *Transaction) Validate() error { // validation logic here return nil } In this example, we're defining a Validate method on the Transaction struct that takes no arguments and returns an error.
Build it
Now that we've covered the basics of Go's type system, structs, and methods, let's build a simple example that demonstrates how to use these concepts to model data.
Step 1: Define the struct
Define a Transaction struct with the following fields: ID, Amount, Currency, and Timestamp.
type Transaction struct { ID string Amount float64 Currency string Timestamp time.Time } Step 2: Add a method to the struct
Add a Validate method to the Transaction struct that checks if the Amount field is greater than zero.
func (tx *Transaction) Validate() error { if tx.Amount <= 0 { return errors.New("amount must be greater than zero") } return nil } Step 3: Create a new struct instance
Create a new instance of the Transaction struct and call the Validate method on it.
tx := &Transaction{ ID: "12345", Amount: 10.99, Currency: "USD", Timestamp: time.Now(), } err := tx.Validate() if err != nil { log.Println(err) } When this breaks
There are several ways that this code could break. Here are a few examples:
- If the
Amountfield is not greater than zero, theValidatemethod will return an error. - If the
Timestampfield is not set, theValidatemethod may panic when trying to access it. - If the
Currencyfield is not a valid currency code, theValidatemethod may return an error.
To fix these issues, you could add additional validation logic to the Validate method to check for these conditions.
What it costs
Using Go's type system, structs, and methods to model data has several benefits, including:
- Improved code readability and maintainability
- Reduced risk of errors due to type mismatches
- Improved performance due to the use of structs instead of maps
However, it also has some costs, including:
- Increased complexity due to the need to define and manage custom types
- Potential performance overhead due to the use of method calls instead of direct field access
In the interview
In an interview, you might be asked to explain how you would model data in Go using structs and methods. A weak answer might focus on the syntax of defining a struct and adding methods, without discussing the benefits and trade-offs of using this approach.
A stronger answer would discuss the benefits of using Go's type system, structs, and methods to model data, such as improved code readability and maintainability, and reduced risk of errors. It would also discuss the potential costs, such as increased complexity and potential performance overhead.
For example, an interviewer might ask:
"Can you explain how you would model data in Go using structs and methods?"
A weak answer might be:
"You define a struct using the struct keyword, and then you can add methods to it using the func keyword. For example, type Transaction struct { ... } and func (tx *Transaction) Validate() error { ... }."
A stronger answer would be:
"When modeling data in Go, I prefer to use structs and methods because it allows me to define a clear and consistent interface for my data, which improves code readability and maintainability. Additionally, using Go's type system helps reduce the risk of errors due to type mismatches. However, I also consider the potential costs, such as increased complexity and potential performance overhead, and try to balance these trade-offs when designing my data models."
Your tasks
- Define a
Userstruct with fields forID,Name, andEmail, and add aValidatemethod to it that checks if theEmailfield is a valid email address. - Create a new instance of the
Userstruct and call theValidatemethod on it. - Modify the
Validatemethod to also check if theNamefield is not empty. - Discuss the benefits and trade-offs of using Go's type system, structs, and methods to model data, and provide an example of how you would use this approach in a real-world application.
Your tasks this week
Do the exercises above before the next chapter. Reading a tutorial and doing
one are different activities and only one of them changes what you can build.
Stuck on any of them? Say so — describe what you tried and what happened:
tell me where you got stuck. I read every one, and the questions
that come back more than twice get answered in the next chapter.
Go, from zero to a running service
Chapter 3 of 12. New chapter every Tuesday night.
Next: Slices and maps: how they actually behave.
· The full syllabus and every chapter so far
· Subscribers also get the condensed notes for this chapter, the running
recap of everything the series has covered, and the extended guidance:
subscribe
Written by Amit Chakraborty — founding engineer and senior architect: React Native, AI and RAG systems, production architecture. Portfolio · LinkedIn · GitHub.
Need this built, reviewed or taught to your team? Get in touch or email amit@devamit.co.in. Available for senior and founding engineering roles, consulting and training, remote worldwide.
