编辑代码

package main

import (
    "fmt"
)

// 定义学习者接口
type Studyer interface {
    Study(x []float64)
}

// 定义小学生数据结构
type Pupil struct {
    Name string
}

// 实现小学生的 Study 方法
func (p *Pupil) Study(x []float64) {
    fmt.Println(p.Name, "正在学习以下科目:")
    fmt.Println("语文、数学、英语、思想品德")
}

// 定义中学生数据结构
type MidStudent struct {
    Name string
}

// 实现中学生的 Study 方法
func (m *MidStudent) Study(x []float64) {
    fmt.Println(m.Name, "正在学习以下科目:")
    fmt.Println("语文、数学、英语、物理、化学、政治、历史、地理")
}

// 定义大学生数据结构
type ColStudent struct {
    Name string
}

// 实现大学生的 Study 方法
func (c *ColStudent) Study(x []float64) {
    fmt.Println(c.Name, "正在学习以下科目:")
    fmt.Println("专业课程、选修课程")
}

// 定义一个接口函数
func PrintStudyContent(s Studyer) {
    s.Study(nil)
}

func main() {
    // 接收用户输入的学生类型
    var sType string
    fmt.Print("请输入学生类型(Pupil、MidStudent、ColStudent):")
    fmt.Scanln(&sType)
    
    // 根据不同的学生类型,输出其学习科目内容
    switch sType {
    case "Pupil":
        p := &Pupil{"Tom"}
        PrintStudyContent(p)
    case "MidStudent":
        m := &MidStudent{"Jerry"}
        PrintStudyContent(m)
    case "ColStudent":
        c := &ColStudent{"Lucy"}
        PrintStudyContent(c)
    default:
        fmt.Println("未知学生类型")
    }
}
package main

import "fmt"

// 定义商品接口
type Good interface {
    settleAccount() float64
    orderInfo() string
}

// 定义手机结构体
type Phone struct {
    name  string
    price float64
}

func (p Phone) settleAccount() float64 {
    return p.price
}

func (p Phone) orderInfo() string {
    return fmt.Sprintf("%s: %.2f", p.name, p.price)
}

// 定义赠品结构体
type FreeGift struct {
    name string
}

func (f FreeGift) settleAccount() float64 {
    return 0
}

func (f FreeGift) orderInfo() string {
    return f.name
}

func main() {
    // 实例化商品
    iphone := Phone{name: "iPhone", price: 999.99}
    earphones := FreeGift{name: "Earphones"}

    // 创建购物车
    cart := []Good{iphone, earphones}

    // 打印购物车中的商品信息
    for _, item := range cart {
        fmt.Println(item.orderInfo())
    }
}