MST

星途 面试题库

面试题:Go函数重构之代码逻辑优化

给定如下Go函数代码: ```go func CalculateScore(students []map[string]interface{}) []map[string]float64 { result := make([]map[string]float64, 0) for _, student := range students { score := 0.0 if mathScore, ok := student["mathScore"].(float64); ok { score += mathScore } if englishScore, ok := student["englishScore"].(float64); ok { score += englishScore } subResult := make(map[string]float64) subResult["totalScore"] = score result = append(result, subResult) } return result } ``` 请对该函数进行重构,提高代码的可读性和可维护性,要求使用更合理的变量命名、减少重复代码,并适当添加注释。
13.2万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
// CalculateScore 计算学生的总分数
// 输入为学生信息的切片,每个学生信息是一个map,包含"mathScore"和"englishScore"字段
// 返回每个学生总分数的切片,每个元素是一个map,包含"totalScore"字段
func CalculateScore(students []map[string]interface{}) []map[string]float64 {
    var results []map[string]float64
    for _, student := range students {
        totalScore := calculateTotalScore(student)
        result := map[string]float64{
            "totalScore": totalScore,
        }
        results = append(results, result)
    }
    return results
}

// calculateTotalScore 计算单个学生的总分数
func calculateTotalScore(student map[string]interface{}) float64 {
    var totalScore float64
    addScore(&totalScore, student, "mathScore")
    addScore(&totalScore, student, "englishScore")
    return totalScore
}

// addScore 将指定科目分数加到总分数上
func addScore(totalScore *float64, student map[string]interface{}, subject string) {
    if score, ok := student[subject].(float64); ok {
        *totalScore += score
    }
}