Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

“error: expected item, found 'let'”

Tags:

I have a code dump where i put examples for rust code in case I forget something. I keep getting error: expected item, found 'let' for line 41+. could it be my code isn't structured properly? I simply pasted snips of code I learned about into the main.rs. I suppose enums have some sort of special formatting or place.

I tried changing the names, thinking it was name convention; but that didn't help. Same error.

Here's the dump (not that big actually yet)

#[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);
like image 310
The User Avatar asked Mar 22 '15 23:03

The User


1 Answers

Your fundamental issue is that let can only be used in a function. So, wrapping the code in main(), and also fixing the style:

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);
 }
like image 80
Steve Klabnik Avatar answered Oct 21 '22 05:10

Steve Klabnik