Explain the use of Go's structs and composition for defining and using composite types and structures in Go programs?
In Go, a struct is a composite data type that groups together zero or more values of different types. It is similar to a class in other languages, but without inheritance or methods attached to it.
Structs are defined using the **type**
keyword, followed by the name of the struct, and then the fields inside curly braces **{}**
. Here's an example of a struct definition:
type Person struct {
Name string
Age int
}
This defines a new struct type **Person**
, which has two fields, **Name**
of type **string**
, and **Age**
of type **int**
.
Structs can also be composed by embedding one or more types within another type. This is similar to inheritance in object-oriented programming, but without the concept of subtyping. Here's an example:
type Employee struct {
Person
Salary float64
}
This defines a new struct type **Employee**
, which embeds the **Person**
struct as a field, and also has an additional field **Salary**
of type **float64**
. This allows an **Employee**
to have all the fields and methods of a **Person**
, as well as its own fields and methods.
Composition can also be used to implement interfaces in Go. By embedding a type that implements an interface, a struct can automatically implement that interface as well. Here's an example:
type Animal interface {
Speak() string
}
type Dog struct {
Name string
}
func (d Dog) Speak() string {
return "Woof!"
}
type Bulldog struct {
Dog
}
func main() {
var b Bulldog
fmt.Println(b.Speak()) // Output: Woof!
}
In this example, **Dog**
is a struct that implements the **Animal**
interface by defining a **Speak()**
method that returns "Woof!". **Bulldog**
is a new struct type that embeds **Dog**
, and therefore also has a **Speak()**
method that returns "Woof!". Because **Bulldog**
has a **Speak()**
method, it can be used as an **Animal**
as well.
This is an example of how composition and interfaces can be used together to achieve polymorphism in Go.