Go (Golang) / Object-Oriented Programming in Go
Defining and Using Structs in Go
In this tutorial, you will learn how to define and use structs in Go. We will cover how to create your own types using structs, and how to define methods on these types.
Section overview
5 resourcesExplores how Go implements object-oriented concepts using structs and interfaces.
1. Introduction
In this tutorial, we will explore structs in the Go programming language. Structs allow us to create our own complex types that aggregate together values of other types. They are the building blocks for creating objects and classes in Go.
What you will learn:
- What are structs in Go?
- How to define and create structs.
- How to define methods on structs.
Prerequisites:
- Basic understanding of the Go programming language.
- Familiarity with Go's basic data types (int, float, string, etc.).
2. Step-by-Step Guide
A struct in Go is a user-defined type which allows us to group/combine items of possibly different types into a single type. You can consider a struct a lightweight class that supports encapsulation but lacks inheritance.
Defining a Struct
To define a struct, we use the type keyword, followed by the name of the struct, the struct keyword, and a pair of curly braces {}. Inside the braces, we define the fields of the struct, each on its own line and followed by its type.
For example:
type Person struct {
Name string
Age int
}
Here, Person is a struct that contains two fields: Name of type string, and Age of type int.
Creating Struct Instances
To create a new instance of a struct, we use the Person type followed by a pair of curly braces {}. Inside the braces, we initialize each field with a value.
For example:
p := Person{
Name: "John",
Age: 30,
}
fmt.Println(p) // prints: {John 30}
Defining Methods on Structs
In Go, you can define methods on user-defined types. A method is a function that has a special receiver argument. The receiver appears in its own argument list between the func keyword and the method name.
For example:
func (p Person) SayHello() {
fmt.Println("Hello, my name is", p.Name)
}
Here, SayHello is a method on the Person struct. We can call this method on instances of Person:
p := Person{Name: "John", Age: 30}
p.SayHello() // prints: Hello, my name is John
3. Code Examples
Let's go through a few practical examples.
Example 1: Defining and Using a Struct
// Define a new struct type
type Employee struct {
ID int
Name string
Position string
}
// Create an instance of Employee
e := Employee{
ID: 1,
Name: "John Doe",
Position: "Developer",
}
// Access fields in the struct
fmt.Println(e.Name) // prints: John Doe
Example 2: Using Methods on Structs
// Define a new struct type
type Rectangle struct {
Width float64
Height float64
}
// Define a method to calculate the area of the rectangle
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// Create an instance of Rectangle
r := Rectangle{Width: 10, Height: 20}
// Call the Area method
fmt.Println(r.Area()) // prints: 200
4. Summary
In this tutorial, you learned:
- What structs are in Go and how to define them.
- How to create instances of your struct types.
- How to define methods on your struct types.
Next, you could explore more about how to use pointers with structs, anonymous structs, and nested structs.
5. Practice Exercises
-
Define a
Circlestruct with aRadiusfield. Then, define a methodAreathat calculates the area of the circle (hint:Area = πr^2). -
Define a
Bookstruct withTitle,Author, andPagesfields. Then, define a methodSummarythat returns a string summary of the book. -
Define a
Trianglestruct withBaseandHeightfields. Then, define a methodAreathat calculates the area of the triangle (hint:Area = 0.5 * Base * Height).
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article