- read

Getting Started with Go — Maps, Structs, Error Handling, Logging & Testing

N Nikitins 49

Getting Started with Go — Maps, Structs, Error Handling, Logging & Testing

N Nikitins
Level Up Coding
Published in
7 min read1 day ago

--

Hello, Pioneers of Code! 👋👩‍💻 Are you set to scale up your Go skills? We’re back to feed your curiosity with Maps, Structs, and some Advanced Error Handling! So gear up, fellow Gophers, ’cause we’re ready to dig deeper! ⛏️ 💻

Previously on …

Understanding Structs

Structs are a fundamental data type in Go, used for grouping together related fields with different data types. They allow you to create custom composite data structures. In this section, we’ll dive into structs and provide you with practical examples to help you understand how they work.

Defining a Struct

To define a struct in Go, you specify its fields and their types:

type Person struct {
FirstName string
LastName string
Age int
}

This Person struct has three fields: FirstName, LastName, and Age.

Creating Struct Instances

You can create instances of the Person struct and initialize its fields like this:

p1 := Person{
FirstName: "John",
LastName: "Doe",
Age: 30,
}

p2 := Person{"Jane", "Smith", 25} // Order matters in this case

Accessing Struct Fields

You can access the fields of a struct using dot notation:

fmt.Println(p1.FirstName) // Outputs: John
fmt.Println(p2.Age) // Outputs: 25

Struct Methods

Go allows you to define methods associated with a struct. Here’s an example:

func (p Person) GetFullName() string {
return p.FirstName + " " + p.LastName
}

fullName := p1.GetFullName()

This GetFullName method takes a Person instance and returns their full name as a string.

Maps and the make() Function