1. Introduction
In Golang, structs and interfaces are two fundamental concepts used for different purposes in structuring programs. A struct (short for structure) is a composite data type that groups together variables (fields) under a single name, providing a way to handle related data. An interface, on the other hand, is a type that specifies a method set, defining behavior but not implementation. It represents a set of method signatures and is used to express a contract or a capability.
2. Key Points
1. Composition: Structs are about data composition, and interfaces are about method definition.
2. Implementation: Structs can have concrete data and methods, interfaces only define method signatures.
3. Usage: Structs are used to model concrete things, and interfaces to define capabilities or behaviors.
4. Polymorphism: Interfaces enable polymorphism, allowing different structs to be treated uniformly based on shared behavior.
3. Differences
Characteristic | Struct | Interface |
---|---|---|
Composition | Data composition | Method definition |
Implementation | Concrete data and methods | Method signatures only |
Usage | Model concrete things | Define capabilities/behaviors |
Polymorphism | Not directly related | Enables polymorphism |
4. Example
// Example of a Struct
type Car struct {
Make string
Model string
}
// Example of an Interface
type Vehicle interface {
Drive() string
}
// Implementing an Interface
func (c Car) Drive() string {
return "Driving a " + c.Make + " " + c.Model
}
Output:
Struct Output: Car{Make: "Toyota", Model: "Corolla"} Interface Output: Implementation of Drive() method for Car
Explanation:
1. The Car struct is a concrete representation of a car with Make and Model as its properties.
2. The Vehicle interface defines a behavior (Drive), but not how it's implemented. The Car struct then implements this behavior.
5. When to use?
- Use structs when you need to group data and create concrete objects with specific properties.
- Use interfaces to define behaviors and capabilities, and when you need polymorphic behavior, allowing different structs to be treated uniformly based on shared behavior.
Comments
Post a Comment
Leave Comment