Structs in Go
Go: Structs
In Go, a struct is a user-defined type that represents a collection of fields. Each field has a name and a type, and the fields are defined inside the curly braces that define the struct.
how to define a struct in Go:
type Person struct {
Name string
Age int
Email string
}
In this example, we define a struct called Person
that has three fields: Name
(a string), Age
(an integer), and Email
(a string).
Create a new instance of struct
you can use the following syntax:
p := Person{
Name: "John Doe",
Age: 30,
Email: "johndoe@example.com",
}
In this example, we create a new instance of the "Person" struct and initialize its fields with the values provided.
How to access the fields of a struct
You can access the fields of a struct using the dot notation, like this:
fmt.Println(p.Name) // Output: John Doe
fmt.Println(p.Age) // Output: 30
fmt.Println(p.Email) // Output: johndoe@example.com
How to pass structs as parameters to functions
You can also pass structs as parameters to functions, and return structs from functions like below example
func PrintPerson(p Person) {
fmt.Println(p.Name, p.Age, p.Email)
}
func NewPerson(name string, age int, email string) Person {
return Person{
Name: name,
Age: age,
Email: email,
}
}
In these examples, we define a function called PrintPerson
that takes a Person
struct as a parameter and prints its fields, and a function called NewPerson
that creates a new instance of the Person
struct and returns it.
There are many more things you can do with structs, such as embedding one struct inside another, using methods to define behavior for a struct, and more. I encourage you to check out the official Go documentation for more details!
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go