To embed built-in types into custom structs in Go, you can use struct composition. Here's an example of how to embed built-in types like int
and string
into a custom struct:
package main
import "fmt"
type Person struct {
Name string
Age int
Address Address // Embedding struct Address
}
type Address struct {
Street string
City string
ZipCode int
}
func main() {
// Creating a new Person with embedded Address
person := Person{
Name: "John Doe",
Age: 30,
Address: Address{
Street: "123 Main St",
City: "New York",
ZipCode: 10001,
},
}
fmt.Println(person.Name)
fmt.Println(person.Age)
fmt.Println(person.Address.Street)
fmt.Println(person.Address.City)
fmt.Println(person.Address.ZipCode)
}
In the above example, the Person
struct includes an embedded Address
struct, which in turn has embedded built-in types like string
and int
. You can access the embedded types directly using dot notation, as shown in the main
function.