In Go, you can create a wrapper type using embedding. Embedding allows you to include one struct inside another, making it possible to extend or modify the behavior of the embedded struct. Here's an example of how you can create a wrapper type using embedding:
package main
import "fmt"
// Define the original struct that needs to be wrapped
type OriginalStruct struct {
Field1 string
Field2 int
}
// Create the wrapper struct that embeds OriginalStruct
type WrapperStruct struct {
OriginalStruct
AdditionalField string
}
// Define a method for the wrapper struct
func (w WrapperStruct) PrintFields() {
fmt.Println("OriginalStruct.Field1:", w.Field1)
fmt.Println("OriginalStruct.Field2:", w.Field2)
fmt.Println("AdditionalField:", w.AdditionalField)
}
func main() {
// Create an instance of the wrapper struct
wrapper := WrapperStruct{
OriginalStruct: OriginalStruct{
Field1: "Hello",
Field2: 42,
},
AdditionalField: "World",
}
// Use the method defined in the wrapper struct
wrapper.PrintFields()
}
In the example above, OriginalStruct
is the struct you want to wrap. WrapperStruct
is created with an embedded OriginalStruct
and an additional field called AdditionalField
. The PrintFields
method is defined for the WrapperStruct
to print all the fields, including the ones from OriginalStruct
.
By creating the wrapper type, you can extend the functionality of the original struct or modify its behavior. In this case, the ability to add an AdditionalField
to the OriginalStruct
.