You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中字符串反转后与原串比较为何触发编译错误?

Rust回文判断的所有权错误修复

错误根源

这段代码触发了Rust的所有权规则冲突:reverse函数的参数是String类型,调用reverse(thing)时会把thing的所有权完全转移给函数,但左边的thing == ...还在试图借用这个已经失去所有权的变量,编译器因此抛出E0505错误。

几种修复方法

方法1:让reverse函数接收引用

把reverse的参数改成字符串引用,这样不会转移所有权,只是临时借用原字符串:

fn reverse(s: &str) -> String {
    s.chars().rev().collect()
}
impl Solution {
    pub fn is_palindrome(x: i32) -> bool {
        let thing = x.to_string();
        thing == reverse(&thing)
    }
}

方法2:直接用切片反转,省掉单独函数

没必要单独写reverse函数,直接在判断逻辑里处理,代码更简洁高效:

impl Solution {
    pub fn is_palindrome(x: i32) -> bool {
        let s = x.to_string();
        s.chars().eq(s.chars().rev())
    }
}

或者更紧凑的写法:

impl Solution {
    pub fn is_palindrome(x: i32) -> bool {
        let s = x.to_string();
        s == s.chars().rev().collect::<String>()
    }
}

方法3:克隆字符串(不推荐,有额外性能开销)

如果一定要保留原reverse函数的签名,可以克隆一份thing传给函数,让原变量的所有权得以保留:

fn reverse(s: String) -> String {
    s.chars().rev().collect()
}
impl Solution {
    pub fn is_palindrome(x: i32) -> bool {
        let thing = x.to_string();
        thing == reverse(thing.clone())
    }
}

内容的提问来源于stack exchange,提问作者Nick Hooper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:35:05