编辑代码

package main

import (
    "fmt"
)

type Studyer interface {
    Study(x []float64)
}

type Pupil struct {
    subjects []string
    scores   []float64
}

func (p *Pupil) Study(x []float64) {
    p.subjects = []string{"语文", "数学", "英语", "音乐"}
    p.scores = x
}

type MidStudent struct {
    subjects []string
    scores   []float64
}

func (m *MidStudent) Study(x []float64) {
    m.subjects = []string{"语文", "数学", "英语", "音乐"}
    m.scores = x
}

type ColStudent struct {
    subjects []string
    scores   []float64
}

func (c *ColStudent) Study(x []float64) {
    c.subjects = []string{"语文", "数学", "英语", "音乐"}
    c.scores = x
}

func printStudyResult(s Studyer) {
    switch v := s.(type) {
    case *Pupil:
        fmt.Printf("小学生学习科目: %v\n", v.subjects)
        fmt.Printf("小学生学习成绩: %v\n", v.scores)
    case *MidStudent:
        fmt.Printf("中学生学习科目: %v\n", v.subjects)
        fmt.Printf("中学生学习成绩: %v\n", v.scores)
    case *ColStudent:
        fmt.Printf("大学生学习科目: %v\n", v.subjects)
        fmt.Printf("大学生学习成绩: %v\n", v.scores)
    }
}

func main() {
    var s Studyer
    var scoreList []float64

    fmt.Println("请输入学生类型: 1-小学生;2-中学生;3-大学生")
    var studentType int
    fmt.Scanln(&studentType)

    fmt.Println("请输入成绩(四门科目),用空格隔开:")
    for i := 0; i < 4; i++ {
        var score float64
        fmt.Scan(&score)
        scoreList = append(scoreList, score)
    }

    switch studentType {
    case 1:
        s = &Pupil{}
    case 2:
        s = &MidStudent{}
    case 3:
        s = &ColStudent{}
    }

    s.Study(scoreList)
    printStudyResult(s)
}