Structures records — Field and properties

In Go, structures (structs) are used to group together fields, which are variables associated with different data types. Unlike some other programming languages, Go does not have properties in the traditional sense, but you can achieve similar functionality using struct fields and methods.

Defining Fields in a Struct

Fields in a struct are defined within the struct type. Each field has a name and a type.

Example: Defining a Struct with Fields

package main

import (
    "fmt"
)

// Define the Person struct with fields
type Person struct {
    FirstName string
    LastName  string
    Age       int
}

func main() {
    // Initialize a Person instance
    person := Person{
        FirstName: "Alice",
        LastName:  "Johnson",
        Age:       28,
    }

    // Access and print the fields
    fmt.Printf("First Name: %s\\\\n", person.FirstName)
    fmt.Printf("Last Name: %s\\\\n", person.LastName)
    fmt.Printf("Age: %d\\\\n", person.Age)
}

Explanation

  1. Define the Person Struct:
  2. Initialize a Person Instance:
  3. Access and Print the Fields:

Detailed Output

The output of the above code will be:

First Name: Alice
Last Name: Johnson
Age: 28

Methods for Structs

You can define methods for structs to encapsulate functionality that operates on the struct's fields. Methods in Go are defined with a receiver, which specifies the type the method is associated with.

Example: Defining Methods for a Struct

// Define a method to get the full name of the person
func (p Person) FullName() string {
    return p.FirstName + " " + p.LastName
}

// Define a method to celebrate the person's birthday
func (p *Person) CelebrateBirthday() {
    p.Age += 1
}

func main() {
    // Initialize a Person instance
    person := Person{
        FirstName: "Alice",
        LastName:  "Johnson",
        Age:       28,
    }

    // Use the FullName method
    fmt.Printf("Full Name: %s\\\\n", person.FullName())

    // Celebrate the person's birthday
    person.CelebrateBirthday()
    fmt.Printf("New Age after Birthday: %d\\\\n", person.Age)
}

Explanation

  1. Define a Method to Get the Full Name:
  2. Define a Method to Celebrate the Person's Birthday: