Logo

Developer learning path

Go

Structs in Go

Structs

66

#description

Structs in Go are composite data types that are used to group different types of variables together in order to create a single logical entity. Structs are similar to classes in other object-oriented programming languages, and they are used to create custom data types.

In Go, a struct is defined using the type keyword followed by the name of the struct and its fields enclosed in curly braces.

Here's an example:

                    
type Person struct {
    Name string
    Age int
}
                  

This defines a Person struct with two fields: Name and Age.

We can create instances of this struct like so:

                    
p1 := Person{Name: "John Smith", Age: 30}
                  

We can then access the fields of this struct using dot notation:

                    
fmt.Println(p1.Name, p1.Age) // Output: John Smith 30
                  

Structs can be used in a variety of ways in Go. For example, they can be used to represent data from a database, to pass data between functions, or to create custom data types for use in a program. By grouping related data together into a single entity, structs allow us to write cleaner and more efficient code.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.