How to Create And Use Structs In Golang?

12 minutes read

In Go, a struct is a user-defined composite data type that allows you to group together related fields of different data types. It is similar to a class in object-oriented programming languages.


To create a struct in Go, you use the type keyword followed by the name of the struct and define its fields within curly braces. Each field has a name and a type. Here's an example of creating a struct called Person with two fields, name and age:

1
2
3
4
type Person struct {
    name string
    age  int
}


To create an instance of a struct, you simply initialize it using curly braces and assign values to its fields:

1
p := Person{name: "John", age: 30}


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

1
2
fmt.Println(p.name) // Output: John
fmt.Println(p.age)  // Output: 30


If you try to access a field that has not been assigned a value, it will be zero-valued according to its type.


Structs can also be used as anonymous fields within other structs, allowing for composition:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
type Address struct {
    city    string
    country string
}

type Person struct {
    name    string
    age     int
    address Address
}

p := Person{
    name: "John",
    age:  30,
    address: Address{
        city:    "New York",
        country: "USA",
    },
}

fmt.Println(p.address.city)    // Output: New York
fmt.Println(p.address.country) // Output: USA


Structs in Go can also have methods associated with them. These methods can access and modify the fields of the struct. To define a method on a struct, you declare a function with a receiver type that matches the struct's name:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
type Circle struct {
    radius float64
}

func (c Circle) calculateArea() float64 {
    return 3.14159 * c.radius * c.radius
}

// Usage:
circle := Circle{radius: 5}
area := circle.calculateArea()
fmt.Println(area) // Output: 78.53975


This is just a brief overview of how to create and use structs in Golang. It's a powerful tool for organizing data, and you can perform various operations with structs to build complex programs.

Best Golang Books to Read in 2024

1
Mastering Go: Create Golang production applications using network libraries, concurrency, machine learning, and advanced data structures, 2nd Edition

Rating is 5 out of 5

Mastering Go: Create Golang production applications using network libraries, concurrency, machine learning, and advanced data structures, 2nd Edition

2
Distributed Services with Go: Your Guide to Reliable, Scalable, and Maintainable Systems

Rating is 4.9 out of 5

Distributed Services with Go: Your Guide to Reliable, Scalable, and Maintainable Systems

3
Go Programming Language, The (Addison-Wesley Professional Computing Series)

Rating is 4.8 out of 5

Go Programming Language, The (Addison-Wesley Professional Computing Series)

4
Learning Go: An Idiomatic Approach to Real-World Go Programming

Rating is 4.7 out of 5

Learning Go: An Idiomatic Approach to Real-World Go Programming

5
Event-Driven Architecture in Golang: Building complex systems with asynchronicity and eventual consistency

Rating is 4.6 out of 5

Event-Driven Architecture in Golang: Building complex systems with asynchronicity and eventual consistency

6
Hands-On Software Architecture with Golang: Design and architect highly scalable and robust applications using Go

Rating is 4.5 out of 5

Hands-On Software Architecture with Golang: Design and architect highly scalable and robust applications using Go

7
Head First Go

Rating is 4.4 out of 5

Head First Go


How to define a struct method with a pointer receiver in Golang?

In Go, a pointer receiver is used to modify the value of the struct directly rather than creating a copy of the struct. To define a struct method with a pointer receiver, follow these steps:

  1. Define your struct type:
1
2
3
4
type MyStruct struct {
    field1 int
    field2 string
}


  1. Define the struct method and use a pointer receiver:
1
2
3
4
5
func (s *MyStruct) myMethod() {
    // Modify struct fields as needed
    s.field1 = 10
    s.field2 = "Hello"
}


Note: The receiver in the method signature is defined with a * before the struct name (*MyStruct). This indicates that the method is using a pointer receiver.

  1. Access and call the method using a struct instance:
1
2
3
4
5
6
7
8
func main() {
    myStruct := &MyStruct{}
    myStruct.myMethod()
    
    // Access modified struct fields
    fmt.Println(myStruct.field1) // Output: 10
    fmt.Println(myStruct.field2) // Output: Hello
}


In the example above, myMethod() modifies the struct fields field1 and field2 directly using the pointer receiver (*MyStruct).


How to create a struct in Golang?

In Golang, creating a struct involves defining a new user-defined data type that encapsulates a collection of fields. Here's an example of how to create a struct in Golang:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import "fmt"

// Define a struct type
type Person struct {
    name string
    age  int
}

func main() {
    // Create a new struct instance
    person := Person{name: "John Doe", age: 25}

    // Access struct fields
    fmt.Println("Name:", person.name)
    fmt.Println("Age:", person.age)
}


In the above example, we create a struct type Person with two fields - name (of type string) and age (of type int). Inside the main() function, we create a new struct instance person with specific values for each field. Finally, we access the struct fields using dot notation (person.name, person.age).


Output:

1
2
Name: John Doe
Age: 25


By default, when you initialize a struct, all fields are set to their zero value according to their type. You can also create an anonymous struct (without specifying a name) if you only need it locally within a function.


What is a struct in Golang?

In Golang, a struct is a composite data type that is used to group together zero or more values with different types under a single name. It is similar to classes in other object-oriented programming languages.


A struct is defined using the type keyword followed by the name of the struct and a set of field declarations enclosed in curly braces {}. Each field declaration consists of a name and a type.


Here is an example of defining a struct in Golang:

1
2
3
4
5
type Person struct {
    name string
    age  int
    city string
}


In this example, the Person struct has three fields: name of type string, age of type int, and city of type string.


Once a struct is defined, you can create instances of the struct by declaring variables with the struct type and assigning values to its fields. Accessing the fields of a struct is done using the dot notation (.).

1
2
3
4
person := Person{name: "John", age: 30, city: "New York"}
fmt.Println(person.name) // Output: John
fmt.Println(person.age)  // Output: 30
fmt.Println(person.city) // Output: New York


Structs in Golang support methods, which are functions associated with the struct that can perform operations on its fields. They can be defined using the func keyword followed by the name of the struct, a receiver argument, and the method body.

1
2
3
4
5
6
func (p Person) introduce() string {
    return fmt.Sprintf("Hi, my name is %s and I'm %d years old.", p.name, p.age)
}

person := Person{name: "John", age: 30, city: "New York"}
fmt.Println(person.introduce()) // Output: Hi, my name is John and I'm 30 years old.


Overall, structs in Golang provide a way to define custom data types with multiple fields and methods, allowing for structured data organization and object-oriented programming capabilities.


What is the role of tags in a struct in Golang?

In Go, tags are used to attach metadata to the fields of a struct. They provide a way to annotate and describe the fields of a struct, making it possible to add additional information about the field such as validation rules, database column names, or serialization instructions.


The general syntax for a tag is a string literal placed immediately after the field declaration inside backticks (`). Tags can include any arbitrary string, but commonly they follow a specific format with key-value pairs separated by commas. For example:

1
2
3
4
5
type Person struct {
    Name  string `json:"name" validate:"required"`
    Age   int    `json:"age"`
    Email string `json:"email" validate:"email"`
}


In this example, json and validate are the keys used in the tags. These tags can be accessed and utilized by frameworks, libraries, or functions that work with these struct fields. For instance, when the struct is serialized using the json package, the field names will be converted to lowercase with the values specified in the json tags. Likewise, a validation library can inspect the validate tags to enforce validation rules on the respective fields.


Overall, tags play a crucial role in Go structs by enabling additional metadata and allowing for more sophisticated processing and manipulation of those structs.


What is the zero value of a struct in Golang?

In Go, when a struct is declared and initialized without explicitly assigning any values, each field of the struct takes on its zero value. The zero value depends on the type of the field.


For basic types, such as integers, floats, strings, booleans, and pointers, the zero value is:

  • 0 for integers
  • 0.0 for floats
  • "" (empty string) for strings
  • false for booleans
  • nil for pointers


For struct fields with complex types, such as arrays, slices, maps, and channels, the zero value is:

  • nil for pointers, slices, maps, and channels
  • An empty array, slice, or map (with no elements) for arrays, slices, and maps


It's important to note that the zero value is automatically assigned by Go when a struct is declared and initialized without explicitly setting any values.


How to create a nested struct in Golang?

To create a nested struct in Golang, you can simply define a struct type within another struct type.


Here's an example:

 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
28
29
30
31
32
33
34
35
package main

import "fmt"

type Address struct {
    Street string
    City   string
    State  string
}

type Person struct {
    Name    string
    Age     int
    Address Address
}

func main() {
    // Creating a nested struct object
    p := Person{
        Name: "John Doe",
        Age:  30,
        Address: Address{
            Street: "123 ABC Street",
            City:   "XYZ City",
            State:  "PQR State",
        },
    }

    // Accessing fields of the nested struct
    fmt.Println("Name:", p.Name)
    fmt.Println("Age:", p.Age)
    fmt.Println("Street:", p.Address.Street)
    fmt.Println("City:", p.Address.City)
    fmt.Println("State:", p.Address.State)
}


In this example, Person is a struct that contains a nested struct Address. The fields of the Address struct (Street, City, and State) can be accessed using the dot notation (p.Address.Street, p.Address.City, p.Address.State) within the Person struct.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

To create a new Golang project, follow these steps:Set up your development environment: Install Golang: Download and install the Go programming language from the official website (https://golang.org). Configure Go workspace: Set up your Go workspace by creatin...
In Golang, loops and control structures are essential for controlling the flow of execution in a program. They allow you to iterate through collections of data, perform repetitive tasks, and make decisions based on certain conditions. Here is an overview of ho...
To deploy a Golang application to a server, you can follow the steps outlined below:Choose a server: Begin by selecting a server where you wish to deploy your Golang application. This could be a cloud-based server, a Virtual Private Server (VPS), or a physical...