跟我一起学“仓颉”编程语言-模式匹配
本章为大家详细的介绍了仓颉编程语言中模式匹配的内容。
·
目录
一、通配符模式
通配符模式使用下划线(_)表示,可以匹配任何值,在match表达式中,已经使用过了通配符表达式了,这里就不做过多介绍。
二、常量模式
常量模式包含:整型常量、浮点型常量、字符型常量、字符串常量、布尔常量、Unit常量。
package Study
main () {
let score = "B"
let result = match {
case score == "A" => "优秀"
case score == "B" => "良好"
case score == "C" => "中等"
case score == "D" => "及格"
case score == "E" => "不及格"
case _ => "非法输入"
}
println("${result}")
}
三、绑定模式
package Study
main() {
let x = -10
let y = match (x) {
case 0 => "0"
case n => "n是非0数字: ${n}" // 绑定模式
}
println(y)
}
四、类型模式
类型模式用于判断一个值运行时类型是否是某个类型的子类型。有两种形式:id: Type 和 _: Type
package Study
class Car {
var name = "问界"
}
open class Animal {
var name = "动物"
}
class Cat <: Animal {
init() {
name = "Tom"
}
}
func matchType(value: Any) {
match(value) {
case _: Car => println("问界")
case animal: Animal => println(animal.name)
case _: Cat => println("Tom")
case _ => println("匹配失败")
}
}
main() {
var value: Any = Cat()
matchType(value)
value = Car()
matchType(value)
value = Animal()
matchType(value)
value = 114514
matchType(value)
}
五、元组模式
package Study
func matchTuple(value: (String, Int64)) {
match(value) {
case (name, age) => println("姓名: ${name} 年龄: ${age}")
case ("刘小辉", 23) => println("姓名: 刘小辉 年龄: 23")
}
}
main() {
matchTuple(("余小弓", 23))
matchTuple(("刘小辉", 25))
}
六、枚举模式
枚举模式在枚举类型那里已经给大家介绍了,这里就不在做过多赘述。
七、小结
本章为大家详细的介绍了仓颉编程语言中模式匹配的内容,下一章,为大家带来模式其他用法的内容。最后,创作不易,如果大家觉得我的文章对学习仓颉服务端开发有帮助的话,就动动小手,点个免费的赞吧!收到的赞越多,我的创作动力也会越大哦,谢谢大家🌹🌹🌹!!!
更多推荐
所有评论(0)