In Go, a struct is a composite data type that groups together zero or more values with different data types under one name. Structs are similar to classes in object-oriented programming, and they allow you to create custom data types that can represent complex entities in your program.
A struct definition consists of a list of fields, each of which has a name and a data type. Here's an example of a simple struct definition in Go:
type Person struct {
name string
age int
}
In this example, we define a struct called Person
with two fields: name
of type string and age
of type int. Once we define the struct, we can create new instances of it by setting the values of its fields.
Here's an example of creating a new Person
object from the Person
struct using a constructor function:
func NewPerson(name string, age int) *Person {
p := Person{name: name, age: age}
return &p
}
func main() {
// Create a new Person object using the constructor.
p := NewPerson("John Doe", 30)
// Use dot notation to access fields of Person object.
fmt.Println(p.name, "is", p.age, "years old.")
}
In this example, we define a constructor function called NewPerson
returns a new instance of the Person
struct with given values of name
and age
. We then create a new Person
object using the constructor and assign it to the variable p
.
Finally, we use dot notation to access the name
and age
fields of the Person
objects and print them out to the console.
Here is an updated version of the article with more information about struct data type in Go:
Struct data type in Go
Structs are useful for modeling complex data like customer records, employee records, etc.
Let's see another example.
type Customer struct {
FirstName string
LastName string
Age int
}
You can then create instances of the struct:
customer1 := Customer {
FirstName: "John",
LastName: "Doe",
Age: 30,
}
We can also use struct literal to create instances:
customer2 := Customer{ "Mary", "Smith", 25 }
We can access struct fields using the dot operator:
customer1.FirstName // John
customer1.LastName // Doe
Struct fields can be of any valid Go type - basic types, other structs, slices, maps, functions, interfaces, pointers, etc.
Structs in Go are value types. Assigning one struct to another copies all the fields.
You can also embed one struct inside another to compose structs.
type Address struct {
Street string
City string
}
type Customer struct {
Name string
Address // Embedded struct
Phone string
}
Conclusion
Structs are a powerful feature of Go that allows you to create custom data types to represent your program's entities. They are a key tool for organizing the data in your program and providing more structure to it. With the help of a constructor function, you can easily create new instances of the struct and use them to achieve your app's purpose with ease.
Disclaim: This article is created with ChatGPT
To learn more, visit: sagecode.net
Learn and prosper ๐๐๐ผ