From 3c981f9315ecee8db6e05a19db4302e5c85100fe Mon Sep 17 00:00:00 2001 From: yangyudong <916291030@qq.com> Date: Thu, 10 Apr 2025 17:45:32 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BB=93=E6=9E=84=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 02_core_concepts/02_structs/main.go | 52 +++++++++++++++++++++- 02_core_concepts/03_interfaces/main.go | 60 +++++++++++++++++++++++++- 2 files changed, 108 insertions(+), 4 deletions(-) diff --git a/02_core_concepts/02_structs/main.go b/02_core_concepts/02_structs/main.go index 0db886e..c701aad 100644 --- a/02_core_concepts/02_structs/main.go +++ b/02_core_concepts/02_structs/main.go @@ -1,5 +1,53 @@ package main -func main() { - // TODO +import "fmt" + +// 定义一个Person结构体 +type Person struct { + Name string + Age int +} + +// 给Person结构体定义一个方法 +func (p Person) Greet() { + fmt.Printf("Hello, my name is %s and I'm %d years old.\n", p.Name, p.Age) +} + +// 嵌套结构体示例 +type Employee struct { + Person + JobTitle string +} + +func main() { + // 结构体初始化方式1:字段顺序 + p1 := Person{"Alice", 25} + + // 结构体初始化方式2:字段名指定 + p2 := Person{ + Name: "Bob", + Age: 30, + } + + // 访问结构体字段 + fmt.Println(p1.Name) // Alice + fmt.Println(p2.Age) // 30 + + // 调用结构体方法 + p1.Greet() // Hello, my name is Alice and I'm 25 years old. + p2.Greet() // Hello, my name is Bob and I'm 30 years old. + + // 嵌套结构体初始化 + emp := Employee{ + Person: Person{ + Name: "Charlie", + Age: 35, + }, + JobTitle: "Developer", + } + + // 访问嵌套结构体字段 + fmt.Println(emp.Name) // Charlie (提升字段) + fmt.Println(emp.JobTitle) // Developer + emp.Greet() // Hello, my name is Charlie and I'm 35 years old. } diff --git a/02_core_concepts/03_interfaces/main.go b/02_core_concepts/03_interfaces/main.go index 0db886e..f4caadf 100644 --- a/02_core_concepts/03_interfaces/main.go +++ b/02_core_concepts/03_interfaces/main.go @@ -1,5 +1,61 @@ package main -func main() { - // TODO +import "fmt" + +// 定义一个接口 +type Shape interface { + Area() float64 +} + +// 定义一个结构体:Rectangle +type Rectangle struct { + Width, Height float64 +} + +// 实现接口方法:Area +func (r Rectangle) Area() float64 { + return r.Width * r.Height +} + +// 定义另一个结构体:Circle +type Circle struct { + Radius float64 +} + +// 实现接口方法:Area +func (c Circle) Area() float64 { + return 3.14 * c.Radius * c.Radius +} + +func main() { + // 创建接口类型的切片 + shapes := []Shape{ + Rectangle{Width: 10, Height: 5}, + Circle{Radius: 7}, + } + + shapes2 := []Shape{ + Rectangle{Width: 20, Height: 10}, + Circle{Radius: 14}, + Rectangle{Width: 30, Height: 15}, + Rectangle{5, 5}, + } + + // 遍历并调用接口方法 + for _, shape := range shapes { + fmt.Printf("Shape Area: %.2f\n", shape.Area()) + } + + // i := 0 + // for { + // fmt.Printf("Shape Area: %.2f\n", shapes2[i].Area()) + // i++ + // if i >= len(shapes2) { + // break + // } + // } + + for _, shape := range shapes2 { + fmt.Printf("%.2f\n", shape.Area()) + } }