【问题标题】:error[E0308]: mismatched types expected `()`, found `bool`. How to remove this error?错误[E0308]:预期类型不匹配 `()`,发现 `bool`。如何消除此错误?
【发布时间】:2021-06-04 09:15:03
【问题描述】:

检查回文的程序

pub fn is_palindrome(str: &str, start: i32, end: i32) -> bool

{

    //if empty string
    if str.is_empty() {
        true
    }

    // If there is only one character
    if start == end {
        true
    }

    // If first and last
    // characters do not match
    if str.chars().nth(start as usize) != str.chars().nth(end as usize) {
        false
    }

    // If there are more than
    // two characters, check if
    // middle substring is also
    // palindrome or not.
    if start < end + 1 {
        is_palindrome(str, start + 1, end - 1)
    }
    true
}

这是我在返回语句中收到错误的代码。 它说 错误[E0308]:类型不匹配 预期(),发现bool 请告诉如何解决这个问题。

【问题讨论】:

  • “我在返回语句中出错” - 什么返回语句?

标签: types rust return boolean palindrome


【解决方案1】:

如果您想从函数中更早地返回值,您忘记了必须使用的return statements(另请参阅Functions):

pub fn is_palindrome(str: &str, start: i32, end: i32) -> bool {

    //if empty string
    if str.is_empty() {
        return true;
    }

    // If there is only one character
    if start == end {
        return true;
    }

    // If first and last
    // characters do not match
    if str.chars().nth(start as usize) != str.chars().nth(end as usize) {
        return false;
    }

    // If there are more than
    // two characters, check if
    // middle substring is also
    // palindrome or not.
    if start < end + 1 {
        return is_palindrome(str, start + 1, end - 1);
    }
    true
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 2022-08-02
    相关资源
    最近更新 更多