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
Explanation of the Code
Struct Definition:
- The
Userstruct represents a user with three attributes:ID,Name, andAge.
- The
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.
Creating and Using the Struct:
- An instance of
Useris created with initial values. - Methods are called to interact with the instance, modifying its attributes and performing operations.
- An instance of
Output of the Program
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