【问题标题】:“error: expected item, found 'let'”“错误:预期的项目,发现'让'”
【发布时间】:2015-03-23 09:59:59
【问题描述】:

我有一个代码转储,我在其中放置了 rust 代码的示例,以防我忘记了什么。我不断收到error: expected item, found 'let' 41+ 行。 可能是我的代码结构不正确吗?我只是将我学到的代码片段粘贴到 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);

【问题讨论】:

标签: rust


【解决方案1】:

您的基本问题是 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);
 }

【讨论】:

  • 认为你可以在函数之外使用变量,类似于 java
  • 是真的吗?我不认为你可以在 Java 中使用类之外的任何东西。
  • 我的意思是在方法/功能之外(它们是一样的吗?)。不是说课外..
  • 对于从搜索声明全局常量中出来的人:OP 想要的代码是 static y: (i8, &str) = (1, "hello");。不,你不能让编译器推断类型。这很糟糕,我知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多