rust - 匹配 `&str` 的开头
问题描述
我想在字符串切片的开头执行匹配。我目前的做法是
fn main() {
let m = "true other stuff";
if m.starts_with("true") { /* ... */ }
else if m.starts_with("false") { /* ... */ }
}
但这比我喜欢的要冗长。另一种方法是
fn main() {
match "true".as_bytes() {
[b't', b'r', b'u', b'e', ..] => { /* ... */ },
[b'f', b'a', b'l', b's', ,'e', ..] => { /* ... */ },
_=> panic!("no")
}
}
但我不想手动将每个模式写成字节数组。这里有更好的方法吗?
解决方案
你可以使用starts_with
str的方法。
fn main() {
match "true" {
s if s.starts_with("true") => { /* ... */ },
s if s.starts_with("false") => { /* ... */ },
_ => panic!("no")
}
}
推荐阅读
- javascript - 当文本在 TextInput 中时,如何禁用 react-native AutoCorrect?
- angular6 - 单击提交按钮后如何在弹出窗口中显示表单数据
- css - 如何将“=>”格式化成图片中的样子?
- php - Laravel - 控制器在使用 Redirect::to 返回时未设置一些变量
- javascript - 尝试优化我的代码以删除嵌套循环或使其更高效
- python-3.x - 简单的 Python 文件 I/O 拼写检查程序
- node.js - 更改 express (node.js) 服务器的默认本地主机 IP 地址 (127.0.0.1)
- powerbi - 我可以将自定义值传递给 Power BI 中的计算列吗?
- php - Laravel Job - 在每个作业开始和失败时执行命令的最佳方式
- laravel-5.8 - 中间件认证除了抛出错误方法