跟我一起学“仓颉”编程语言-match表达式
本章为大家详细的介绍了仓颉编程语言中match表达式的内容。
·
目录
之前在枚举类型那里,我们已经使用match表达式了,下面给大家详细介绍match表达式的内容。
一、match表达式
match表达式包含:有待匹配值的match表达式和无待匹配值的match表达式
有待匹配值的match表达式
package Study
main () {
// 角度
let angle = 45
match (angle) {
case _ where angle >= 0 && angle < 90 => println("${angle}是锐角")
case _ where angle >90 && angle < 180 => println("${angle}是钝角")
case _ where angle == 180 => println("${angle}是平角")
case _ where angle == 360 => println("${angle}是周角")
case _ => println("${angle}是直角")
}
}
注意:where表达式具有补充条件的作用,在循环结构里也可以使用。
无待匹配值的match表达式
package Study
main () {
let score = 79
match {
case score < 0 || score > 100 => println("${score}是非法成绩")
case score < 60 => println("${score}是不及格")
case score < 70 => println("${score}是及格")
case score < 80 => println("${score}是中等")
case score < 90 => println("${score}是良好")
case _ => println("${score}是优秀")
}
}
二、match表达式的类型
在仓颉语言中,任何表达式都是有值的,match表达式类型是Unit,值为()。
简单的修改上述代码
package Study
main () {
let score = 79
var str = ""
let result = match {
case score < 0 || score > 100 => str = "${score}是非法成绩"
case score < 60 => str = "${score}是不及格"
case score < 70 => str = "${score}是及格"
case score < 80 => str = "${score}是中等"
case score < 90 => str = "${score}是良好"
case _ => str = "${score}是优秀"
}
println("${str}")
println("${result}")
}
match表达式支持模式匹配(后面会详细介绍),因此可以把上述代码修改成
package Study
main () {
let score = 79
let result: String = match {
case score < 0 || score > 100 => "${score}是非法成绩"
case score < 60 => "${score}是不及格"
case score < 70 => "${score}是及格"
case score < 80 => "${score}是中等"
case score < 90 => "${score}是良好"
case _ => "${score}是优秀"
}
println("${result}")
}
三、小结
本章为大家详细的介绍了仓颉编程语言中match表达式的内容,下一章,为大家带来模式匹配的内容。最后,创作不易,如果大家觉得我的文章对学习仓颉服务端开发有帮助的话,就动动小手,点个免费的赞吧!收到的赞越多,我的创作动力也会越大哦,谢谢大家🌹🌹🌹!!!
更多推荐
所有评论(0)