main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package main
  2. import "fmt"
  3. // 1. 接口只约定需要什么方法,不规定结构体有哪些字段。
  4. type Introducer interface {
  5. Introduce() string
  6. }
  7. type Student struct {
  8. Name string
  9. }
  10. // 方法签名符合接口要求,Student 就自动实现 Introducer。
  11. func (student Student) Introduce() string {
  12. return "我是学生:" + student.Name
  13. }
  14. type Teacher struct {
  15. Name string
  16. Subject string
  17. }
  18. func (teacher Teacher) Introduce() string {
  19. return fmt.Sprintf("我是老师:%s,教授%s", teacher.Name, teacher.Subject)
  20. }
  21. // 2. 函数依赖接口,不限定必须传 Student 或 Teacher。
  22. // 调用方负责传入可正常使用的实现,而不是 nil。
  23. func introduction(person Introducer) string {
  24. return person.Introduce()
  25. }
  26. // 3. 指针接收者示例:只有 *Assistant 实现这个接口。
  27. type Assistant struct {
  28. Name string
  29. }
  30. func (assistant *Assistant) Introduce() string {
  31. // 本方法特意支持 nil 指针,其他实现不一定支持。
  32. if assistant == nil {
  33. return "助教信息为空"
  34. }
  35. return "我是助教:" + assistant.Name
  36. }
  37. func main() {
  38. fmt.Println("=== 不同类型实现同一个接口 ===")
  39. student := Student{Name: "小朱"}
  40. teacher := Teacher{Name: "王老师", Subject: "Go"}
  41. fmt.Println(introduction(student))
  42. fmt.Println(introduction(teacher))
  43. fmt.Println("\n=== 接口变量与动态类型 ===")
  44. var person Introducer = student
  45. fmt.Printf("实际类型:%T,介绍:%s\n", person, person.Introduce())
  46. person = teacher
  47. fmt.Printf("实际类型:%T,介绍:%s\n", person, person.Introduce())
  48. fmt.Println("\n=== 接口切片 ===")
  49. people := []Introducer{student, teacher, &Assistant{Name: "小陈"}}
  50. for _, item := range people {
  51. fmt.Println(introduction(item))
  52. }
  53. fmt.Println("\n=== 接口与 nil ===")
  54. var empty Introducer
  55. fmt.Printf("未赋值接口为 nil:%t\n", empty == nil)
  56. // empty.Introduce() // 没有实际实现,调用会 panic。
  57. var assistant *Assistant
  58. person = assistant // 保存了具体类型 *Assistant,即使其中的指针值为 nil。
  59. fmt.Printf("保存 nil 指针后,接口为 nil:%t\n", person == nil)
  60. fmt.Println(person.Introduce())
  61. }