Tuesday, 14 January 2025

Golang, Gin: Struct

Use a Struct (like Class) to encapsulate dependencies, methods, and functionality.

Here's an example of a single struct with attributes and methods in Go to demonstrate how a struct can encapsulate both data (attributes) and behavior (methods).

Example: Single Struct with Attributes and Methods

package main import ( "fmt" ) ================================= // User struct with attributes and methods type User struct { ID int Name string Age int } ================================= // Method: Displays user details func (u *User) DisplayDetails() { fmt.Printf("User ID: %d\n", u.ID) fmt.Printf("Name: %s\n", u.Name) fmt.Printf("Age: %d\n", u.Age) } ================================= // Method: Updates the user's name func (u *User) UpdateName(newName string) { u.Name = newName fmt.Println("Name updated successfully!") } ================================= // Method: Checks if the user is an adult func (u *User) IsAdult() bool { return u.Age >= 18 } ================================= func main() { // Create a new User instance user := User{ ID: 1, Name: "John Doe", Age: 25, } // Call methods on the User struct fmt.Println("Initial User Details:") user.DisplayDetails() // Update the user's name user.UpdateName("Jane Doe") fmt.Println("\nUpdated User Details:") user.DisplayDetails() // Check if the user is an adult if user.IsAdult() { fmt.Println("\nThe user is an adult.") } else { fmt.Println("\nThe user is not an adult.") } }

Explanation of the Code

  1. Struct Definition:

    • The User struct represents a user with three attributes: ID, Name, and Age.
  2. Methods:

    • DisplayDetails: Prints the user's details to the console.
    • UpdateName: Updates the user's name to a new value.
    • IsAdult: Checks if the user's age is 18 or older and returns a boolean.
  3. Creating and Using the Struct:

    • An instance of User is created with initial values.
    • Methods are called to interact with the instance, modifying its attributes and performing operations.

Output of the Program

Initial User Details: User ID: 1 Name: John Doe Age: 25 Name updated successfully! Updated User Details: User ID: 1 Name: Jane Doe Age: 25 The user is an adult.

Summary

This is how you can use a single struct in Go to encapsulate both data (attributes) and behavior (methods), similar to a class in PHP.

No comments:

Post a Comment

Golang Advanced Interview Q&A