How to Use Structs In Golang?

3 minutes read

In Golang, a struct is a composite data type that allows you to group together different data types under one name. It is similar to a class in object-oriented programming languages.


To define a struct in Golang, you use the type keyword followed by the struct name and the list of fields inside curly braces. For example, you can define a struct called Person with fields Name, Age, and City like this:

1
2
3
4
5
type Person struct {
    Name string
    Age int
    City string
}


You can then create instances of the Person struct by specifying values for each field:

1
2
person1 := Person{Name: "Alice", Age: 30, City: "New York"}
person2 := Person{Name: "Bob", Age: 25, City: "San Francisco"}


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

1
2
fmt.Println(person1.Name) // Output: Alice
fmt.Println(person2.Age) // Output: 25


You can also define methods on a struct by creating functions with a receiver of the struct type:

1
2
3
4
5
6
func (p Person) greet() {
    fmt.Printf("Hello, my name is %s and I am from %s\n", p.Name, p.City)
}

person1.greet() // Output: Hello, my name is Alice and I am from New York
person2.greet() // Output: Hello, my name is Bob and I am from San Francisco


Structs are commonly used in Golang to represent complex data structures and are an essential feature for writing clean and efficient code.


What is a zero-value struct in Golang?

In Golang, a zero-value struct is a struct that has been declared but not initialized. When a struct is declared without explicitly assigning values to its fields, all its fields are set to their zero values. The zero value of a struct is the value that is automatically assigned to all of its fields if no value is provided during initialization.


For example, if we have a struct defined as follows:

1
2
3
4
type Person struct {
    Name string
    Age int
}


And we create a zero-value instance of this struct:

1
var p Person


In this case, the Name field will be initialized to an empty string ("") and the Age field will be initialized to 0, which are their respective zero values.


How to sort an array of structs in Golang?

To sort an array of structs in Golang, you can use the sort.Slice function provided by the sort package. Here's an example of how you can sort an array of structs based on a specific field of the struct:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
	"fmt"
	"sort"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	people := []Person{
		{"Alice", 25},
		{"Bob", 20},
		{"Charlie", 30},
	}

	sort.Slice(people, func(i, j int) bool {
		return people[i].Age < people[j].Age
	})

	for _, person := range people {
		fmt.Println(person.Name, person.Age)
	}
}


In this example, we have a struct Person with two fields Name and Age. We have an array of Person structs called people, which we want to sort based on the Age field. We use the sort.Slice function and provide a sorting function as an argument. The sorting function compares the Age field of two Person structs and returns true if the first person's age is less than the second person's age.


After sorting the array, we iterate over the sorted people array and print out the names and ages of each person.


How to deserialize a struct in Golang?

To deserialize a struct in Golang, you can use the encoding/json package. Here's an example of how to deserialize a struct:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name  string `json:"name"`
	Age   int    `json:"age"`
	Email string `json:"email"`
}

func main() {
	data := []byte(`{"name": "Alice", "age": 30, "email": "alice@example.com"}`)

	var person Person
	err := json.Unmarshal(data, &person)
	if err != nil {
		fmt.Println("Error deserializing JSON:", err)
		return
	}

	fmt.Printf("Deserialized person: %+v\n", person)
}


In this example, we define a struct Person with fields Name, Age, and Email. We then create a JSON string representing a Person object and use json.Unmarshal to deserialize the JSON string into a Person struct.


After deserialization, we can access the fields of the Person struct and print them out.

Facebook Twitter LinkedIn Telegram Whatsapp

Related Posts:

Writing your first Golang program is a simple and straightforward process. Begin by installing Golang on your system and setting up your development environment. This includes creating a new directory for your project and setting your GOPATH.Next, use a text e...
In Golang, parsing JSON data is relatively simple thanks to the encoding/json package provided by the standard library. To parse JSON data in Golang, you will typically create a struct that mirrors the structure of the JSON data you are trying to parse. You ca...
To install Golang on Windows, you can follow these steps:First, download the Golang installer for Windows from the official Golang website.Double-click on the downloaded installer file to open the installation wizard.Follow the on-screen instructions to comple...
Testing code in Golang is an important aspect of the development process to ensure that the application works as intended and to catch any bugs or errors early on. In Golang, testing is done using the built-in testing package, which allows developers to create...
To build a microservice in Golang, you can start by setting up your development environment with the necessary tools like Golang compiler, a package manager like go modules, and an IDE like VSCode.Next, you can create a new project directory, define the projec...