Go 面向对象编程应用实例

    技术2023-10-18  93

    面向对象编程应用实例

    步骤 声明(定义)结构体,确定结构体名编写结构体的字段编写结构体的方法
    案例演示: 编写一个 Student 结构体,包含 name、gender、age、id、score 字段,分别为 string、string、int、int、float64 类型。 结构体中声明一个 say 方法,返回 string 类型,方法返回信息中包含所有字段值。 在 main 方法中,创建 Student 结构体实例(变量),并访问 say 方法,并将调用结果打印输出。 type Student struct { name string gender string age int id int score float64 } func (student *Student) say() string { nfoStr := fmt.Sprintf("student的信息 name=[%v]\ngender=[%v]\nage=[%v]\nid=[%v]\nscore=[%v]", student.name, student.gender, student.age, student.id, student.score) return infoStr } func main() { stu := Student{ name : "tom", gender : "male", age : 18, id : 1000, score : 99.98, } fmt.Println(stu.say()) } 输出结果:  
    盒子案例 1) 编程创建一个 Box 结构体,在其中声明三个字段表示一个立方体的长、宽和高,长宽高要从终端获取 2) 声明一个方法获取立方体的体积。 3) 创建一个 Box 结构体变量,打印给定尺寸的立方体的体积 type Box struct { len float64 width float64 height float64 } //声明一个方法获取立方体的体积 func (box *Box) getVolumn() float64 { return box.len * box.width * box.height } func main() { var box Box box.len = 1.1 box.width = 2.0 box.height = 3.0 volumn := box.getVolumn() fmt.Printf("体积为=%.2f", volumn) } 输出结果:  
    景区门票案例 1) 一个景区根据游人的年龄收取不同价格的门票,比如年龄大于 18,收费 20 元,其它情况门票免费 2) 请编写 Visitor 结构体,根据年龄段决定能够购买的门票价格并输出 type Visitor struct { Name string Age int } func (visitor *Visitor) showPrice() { if visitor.Age >= 90 || visitor.Age <=8 { fmt.Println("考虑到安全,就不要玩了") return } if visitor.Age > 18 { fmt.Printf("游客的名字为 %v 年龄为 %v 收费20元 \n", visitor.Name, visitor.Age) } else { fmt.Printf("游客的名字为 %v 年龄为 %v 免费 \n", visitor.Name, visitor.Age) } } func main() { var v Visitor for { fmt.Println("请输入你的名字") fmt.Scanln(&v.Name) if v.Name == "n" { fmt.Println("退出程序....") break } fmt.Println("请输入你的年龄") fmt.Scanln(&v.Age) v.showPrice() } } 输出结果:  
    Processed: 0.011, SQL: 9