rust - “error: expected item, found ' 让 '”

标签 rust

我有一个代码转储,我在其中放置了 rust 代码的示例,以防我忘记了什么。我不断收到第 41 行以上的 error: expected item, found 'let'。 可能是我的代码结构不正确吗?我只是将我学到的代码片段粘贴到 main.rs 中。我想枚举有某种特殊的格式或位置。

我尝试更改名称,认为这是名称约定;但这没有帮助。同样的错误。

这是转储(实际上还没有那么大)

#[allow(dead_code)]


fn main()
{

}





/////////////////////////////////////////tutorial functoins i made

fn if_statements()
{
    //let (x, y) = (5, 10);
    let x = 5;
    let y = if x == 5 { 10 } else { 15 };
        if y == 15 {println!("y = {}", y);}
}



////////////////////////////////////////// tutoiral functions
#[allow(dead_code)]
fn add(a: i32, b: i32) -> i32
{
    a + b

}

#[allow(dead_code)]
fn crash(exception: &str) -> !
{
    panic!("{}", exception);
}


//TUPLES//
let y = (1, "hello");
let x: (i32, &str) = (1, "hello");

//STRUCTS//
struct Point {
    x: i32,
    y: i32,
}

fn structs() {
    let origin = Point { x: 0, y: 0 }; // origin: Point

    println!("The origin is at ({}, {})", origin.x, origin.y);
}

//ENUMS//
enum Character {
    Digit(i32),
    Other,
}

let ten  = Character::Digit(10);
let four = Character::Digit(4);

最佳答案

您的根本问题是 let 只能在函数中使用。因此,将代码包装在 main() 中,并修复样式:

fn if_statements() {
    let x = 5;

    let y = if x == 5 { 10 } else { 15 };

    if y == 15 {
        println!("y = {}", y);
    }
}

#[allow(dead_code)]
fn add(a: i32, b: i32) -> i32 { a + b }

#[allow(dead_code)]
fn crash(exception: &str) -> ! {
    panic!("{}", exception);
 }

struct Point {
     x: i32,
     y: i32,
}

fn structs() {
    let origin = Point { x: 0, y: 0 };

    println!("The origin is at ({}, {})", origin.x, origin.y);
}

enum Character {
    Digit(i32),
    Other,
}

fn main() {
    let y = (1, "hello");
    let x: (i32, &str) = (1, "hello");

    let ten  = Character::Digit(10);
    let four = Character::Digit(4);
 }

关于rust - “error: expected item, found ' 让 '”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29201370/

相关文章:

rust - Rust lazy_static变量RwLock访问

static - 为什么在同一范围内可以有多个具有静态生命周期的可变引用

返回 Vec<&str> 时字符串的生命周期

rust - 有没有办法从 Rust 程序中检测编译器版本?

Rust 函数没有静态生命周期?

multithreading - 我如何提高 vanilla Rust 中并行代码的低性能?

closures - 将修改其环境的闭包传递给 Rust 中的函数

enums - 如何返回特定索引处的枚举字符串?

rust - 为什么 BufWriter 将内部 Write 包装在一个 Option 中?

rust - 如果函数调用处于rust的panic::catch_unwind中,是否可以返回一个String?