我对rust非常陌生,并尝试编写命令行实用程序作为一种学习方式。
我正在获取args
的列表,并尝试在它们上进行匹配
let args = os::args()
//some more code
match args[1].into_ascii_lower().as_slice() {
"?" | "help" => { //show help },
"add" => { //do other stuff },
_ => { //do default stuff }
}
这导致了这个错误
cannot move out of dereference (dereference is implicit, due to indexing)
match args[1].into_ascii_lower().as_slice() {
^~~~~~~
我不知道这意味着什么,但搜索会产生我没有完全得到的结果,但将args[1]
更改为args.get(1)
会给我另一个错误
error: cannot move out of dereference of `&`-pointer
match args.get(1).into_ascii_lower().as_slice() {
^~~~~~~~~~~
发生了什么事?
正如您在文档中看到的,into_ascii_lower()
的类型是(请参阅此处):
fn into_ascii_upper(self) -> Self;
它直接采用self
,而不是作为参考。这意味着它实际上消耗了字符串并返回了另一个字符串。
因此,当您执行args[1].into_ascii_lower()
时,您尝试直接消耗args
中的一个元素,这是被禁止的。您可能想复制这个字符串,并在此副本上调用into_ascii_lower()
,如下所示:
match args[1].clone().into_ascii_lower().as_slice() {
/* ... */
}