Golang多个if 优化与代码健壮性小技巧

没优化之前: 嵌套if, 检查是否有中文字段值, 否则去查找英文值, 都没有则返回默认值

go 复制代码
if record.City.Names["zh-CN"] == "" {
	city = record.City.Names["en"]
	if record.City.Names["en"] == "" {
		city = record.City.Names["en"]
	}
} else {
	city = "未知地域"
}

优化后: 平级if...else代替嵌套if

go 复制代码
if name, ok := record.City.Names["zh-CN"]; ok {
	city = name
} else if city, ok = record.City.Names["en"]; ok {
	city = record.City.Names["en"]
} else {
	city = "未知地域"
}

知识点: 利用go的ok模式,对查询map对象的值是否存在更加简洁和安全

更进一步的优化, 去掉else

这对else的处理逻辑有明确的值时非常有用

go 复制代码
city = "未知地域"
if name, ok := record.City.Names["zh-CN"]; ok {
	city = name
} else if name, ok = record.City.Names["en"]; ok {
	city = name
}

使用switch代替多个if分支: 根据成绩的分数段给出对应的等级

go 复制代码
func calculateGrade(score int) string {
	var grade string

	if score >= 90 && score <= 100 {
		grade = "A"
	} else if score >= 80 && score < 90 {
		grade = "B"
	} else if score >= 70 && score < 80 {
		grade = "C"
	} else if score >= 60 && score < 70 {
		grade = "D"
	} else if score >= 0 && score < 60 {
		grade = "F"
	} else {
		grade = "Invalid Score"
	}

	return grade
}

优化后: 使代码更加简洁,并且避免了多个嵌套的 if-else 语句。同时,使用 switch 语句还能够处理默认情况,即当 score 不满足任何一个分支条件时,默认返回 "Invalid Score"

go 复制代码
func calculateGrade(score int) string {
	var grade string

	switch {
	case score >= 90 && score <= 100:
		grade = "A"
	case score >= 80 && score < 90:
		grade = "B"
	case score >= 70 && score < 80:
		grade = "C"
	case score >= 60 && score < 70:
		grade = "D"
	case score >= 0 && score < 60:
		grade = "F"
	default:
		grade = "Invalid Score"
	}

	return grade
}

错误检查

首先看etcdgithub官网的错误处理例子:

go 复制代码
resp, err := cli.Put(ctx, "", "")
if err != nil {
	switch err {
	case context.Canceled:
		log.Fatalf("ctx is canceled by another routine: %v", err)
	case context.DeadlineExceeded:
		log.Fatalf("ctx is attached with a deadline is exceeded: %v", err)
	case rpctypes.ErrEmptyKey:
		log.Fatalf("client-side error: %v", err)
	default:
		log.Fatalf("bad cluster endpoints, which are not etcd servers: %v", err)
	}
}

我们可以进一步优化, 使用go自带的包errors对错误类型进行更加健壮的检查, 但是对开发者的要求较高, 需要预定义正确的错误类型, 来保证正确的比较错误

go 复制代码
resp, err := cli.Put(ctx, "", "")
if err2 != nil {
		switch {
		case errors.Is(err, context.Canceled):
			log.Fatalf("ctx is canceled by another routine: %v", err)
		case errors.Is(err, context.DeadlineExceeded):
			log.Fatalf("ctx is attached with a deadline is exceeded: %v", err)
		case errors.Is(err, rpctypes.ErrEmptyKey):
			log.Fatalf("client-side error: %v", err)
		default:
			log.Fatalf("bad cluster endpoints, which are not etcd servers: %v", err)
		}
	}
相关推荐
一 乐20 小时前
校园实验室|基于springboot + vue校园实验室管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
Lisonseekpan20 小时前
Spring Boot Email 邮件发送完全指南
java·spring boot·后端·log4j
sheji341620 小时前
【开题答辩全过程】以 基于Springboot的体检中心信息管理系统设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
天天向上102421 小时前
go 配置热更新
开发语言·后端·golang
狗头大军之江苏分军21 小时前
年底科技大考:2025 中国前端工程师的 AI 辅助工具实战盘点
java·前端·后端
一 乐1 天前
酒店客房预订|基于springboot + vue酒店客房预订系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
计算机毕设指导61 天前
基于Spring Boot的防诈骗管理系统【源码文末联系】
java·spring boot·后端·spring·tomcat·maven·intellij-idea
开心就好20251 天前
IOScer 开发环境证书包括哪些,证书、描述文件与 App ID 的协同管理实践
后端
码事漫谈1 天前
终于找到我想要的远程工具了!
后端
我家领养了个白胖胖1 天前
MCP模型上下文协议 Model Context Protocol & 百度地图MCP开发
java·后端·ai编程