
Structures in GoLang
Structures in GoLang
In Go, a struct is a composite data type that groups together variables (fields) under a single name. Each field in a struct can have a different data type. Structs are used to represent real-world entities with multiple properties.
Key Features of Structures in Go:
- Defined with the
struct
keyword. - Fields can have different types.
- No inheritance, but you can embed structs in other structs (composition).
- Pass by value: When you pass a struct to a function, a copy of the struct is made.
Defining a Struct
A struct is defined using the struct
keyword, followed by the fields of the struct.
fmt.Println(person1) // Output: {"" 0 ""}
Using &
(Address-of operator) to Create a Pointer to a Struct:This allows you to work with references to the struct.
fmt.Println(person1.Name) // Accessing the field through the pointer
Accessing and Modifying Fields
Fields in a struct can be accessed and modified using the dot (.
) notation.
import "fmt"type Person struct { Name string Age int Address string}func main() { person1 := Person{Name: package main
import "fmt"type Person struct { Name string Age int}func (p Person) Greet() { fmt.Println(func main() { person1 := Person{Name: package main
import "fmt"type Person struct { Name string Age int}func (p *Person) HaveBirthday() { p.Age += func main() { person1 := &Person{Name: package main
import "fmt"// Defining the inner structtype Address struct { Street string City string State string}// Defining the outer struct with a nested structtype Person struct { Name string Age int Address Address}func main() { person1 := Person{ Name: package main
import "fmt"func main() { package main
import "fmt"type Person struct { Name string Age int}func main() { package main
import "fmt"import "encoding/json"// Defining struct with tagstype Person struct { Name string `json:"name"` Age int `json:"age"` Gender string `json:"gender"`}func main() { person := Person{Name: "John", Age: 30, Gender: "Male"} // Convert struct to JSON jsonData, _ := json.Marshal(person) fmt.Println(string(jsonData)) // Output: {"name":"John","age":30,"gender":"Male"}}
Summary
- Structs in Go are used to represent objects or entities with multiple properties.
- Fields in structs can have different data types.
- Structs can be passed by value or by reference (using pointers).
- Methods can be defined on structs to encapsulate behavior.
- Go does not support inheritance, but structs can be composed by embedding other structs.
- Struct tags are used for metadata purposes, particularly with libraries like
encoding/json
.
Structs are one of the most important data structures in Go, helping to model complex real-world entities. They allow you to group related data together and apply methods for manipulating this data.