结构体用于定义自定义类型,其中包含一组相关的字段。
```go
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "John Doe", Age: 30}
fmt.Println(p.Name, p.Age)
}
```
接口
接口定义了一组方法的集合,并由其他类型实现。
```go
type Animal interface {
Eat()
Sleep()
}
type Cat struct {}
func (c Cat) Eat() {
fmt.Println("Cat is eating.")
}
func (c Cat) Sleep() {
fmt.Println("Cat is sleeping.")
}
func main() {
var animal Animal
animal = Cat{}
animal.Eat()
animal.Sleep()
}
```