gpt4 book ai didi

Checking the type inside a match statement(检查Match语句中的类型)

转载 作者:bug小助手 更新时间:2023-10-24 17:54:53 34 4
gpt4 key购买 nike



I have a requirement to check the type of a variable inside match statement, What is the best method to do this without using if clauses. A sample code would look like following(the sample code is not working).

我需要检查Match语句中变量的类型,在不使用IF子句的情况下,最好的方法是什么?示例代码将如下所示(示例代码不起作用)。


match (typeof val) {
"time:Date" => {
return "Date";
}
"time:Utc" => {
return "Time:Utc";
}
"time:DateTime" => {
return "DateTime";
}
_ => {
return "Invalid";
}
}

更多回答
优秀答案推荐


You can use a match guard to check for the type similar to an is check in an if-else statement.

您可以使用匹配保护来检查与if-Else语句中的IS检查类似的类型。


function fn(any val) returns string {
match val {
var x if x is time:Date => {
return "Date";
}
// ...
_ => {
return "Invalid";
}
}
}

The match statement does a value match. If your requirement is to purely test for type rather than value, using an if-else statement with is checks may be the better approach.

match语句执行值匹配。如果您的需求是纯粹测试类型而不是值,那么使用带有is检查的if-else语句可能是更好的方法。


function fn(any val) returns string {
if val is time:Date {
return "Date";
}

if val is time:Utc {
return "Time:Utc";
}

// ...

return "Invalid";
}

更多回答

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com