Structs and interfaces are important features in Go that allow you to define custom types and abstract behavior. Here’s an overview of how they work in Go:
1. Structs: A struct is a collection of fields that can be of any type. Structs in Go are declared using the `type` keyword, followed by the struct name and the list of fields enclosed in curly braces. For example:
type Person struct {
Name string
Age int
}
` This code declares a struct called `Person` with two fields, `Name` and `Age`. 2. Creating and accessing structs: Structs are created using the `new` keyword, followed by the struct type. Fields in a struct can be accessed using the dot notation. For example:
“
var p *Person = new(Person)
p.Name = “John”
p.Age = 30
fmt.Println(p.Name, p.Age) // output: John 30
This code creates a new instance of the `Person` struct and sets its `Name` and `Age` fields. It then prints the values of these fields.
3. Interfaces: An interface is a contract that defines a set of methods that a type must implement. Interfaces in Go are declared using the `type` keyword, followed by the interface name and the list of method signatures. For example:
`` type Shape interface { Area() float64 Perimeter() float64 }
“
This code declares an interface called `Shape` with two methods, `Area` and `Perimeter`.
4. Implementing interfaces: A type can implement an interface by providing implementations for all of the methods in the interface. For example:
`` type Rectangle struct { width, height float64 } func (r Rectangle) Area() float64 { return r.width * r.height } func (r Rectangle) Perimeter() float64 { return 2 * (r.width + r.height) }
This code defines a struct called `Rectangle` and provides implementations for the `Area` and `Perimeter` methods of the `Shape` interface. 5. Using interfaces: Interfaces can be used to abstract behavior and allow for more flexible and modular code. For example:
“
func PrintShapeInfo(s Shape) {
fmt.Println(“Area:”, s.Area())
fmt.Println(“Perimeter:”, s.Perimeter())
}
r := Rectangle{width: 10, height: 5}
PrintShapeInfo(r)
This code defines a function called `PrintShapeInfo` that takes a parameter of the `Shape` interface. It then creates a `Rectangle` instance and passes it to the function, which can access the `Area` and `Perimeter` methods of the `Rectangle` through the `Shape` interface.
Structs and interfaces are powerful features in Go that can help you create more expressive and flexible code. By using structs to define custom types with specific fields, and interfaces to define behavior that can be implemented by different types, you can create more modular and reusable code that can adapt to changing requirements.