Error resulting from out-of-scope items

I'm working on this example from a book. It gives me the following error message:

|
6 | println!("{}", basket.apples());
| ^^^^^^ not found in this scope

Both Println!. . . and let basket. . . are inside the main function. I cant seem to figure out why "basket" is out of scope here.

Any help is always appreciated.

fn main ()
{
    println!("double = {}", 5_i32.double());
    println!("double = {}", 5_i64.double());
    
    println!("{}", basket.apples());
    
    let basket = Fruit
    {
        apples: 5,
        bananas: 5,
    };
    
    
}

trait Double
{
    fn double(&self) -> Self;
}

impl Double for i32
{
    fn double(&self) -> Self
    {
        self*2
    }
}

impl Double for i64
{
    fn double(&self) -> Self
    {
        self*2
    }
}



struct Fruit <T>
{
    apples: T,
    bananas: T,
}



impl <T: Double> Double for Fruit <T>
{
    fn double (&self) -> Self
    {
        Fruit
        {
            apples: self.apples.double(),
            bananas: self.apples.double(),
        }
    }
    
}

Please format your code properly using triple backticks.
It says basket is not in scope since it is defined after the println! statement. Move it to before that statement.

2 Likes

Thanks for the response. I've flipped those around as you recommended. I now have another error that I can't seem to solve:
The compiler is telling me that I'm trying to call a method, rather than access a struct field.

  |
14 |     println!("{}", basket.apples());
   |                           ^^^^^^-- help: remove the arguments
   |                           |
   |                           field, not a method
...
41 | struct Fruit <T>
   | ---------------- method `apples` not found for this
fn main ()
{
    println!("double = {}", 5_i32.double());
    println!("double = {}", 5_i64.double());
    
    
    
    let basket = Fruit
    {
        apples: 5,
        bananas: 5,
    };
    
    println!("{}", basket.apples());
    
}

trait Double
{
    fn double(&self) -> Self;
}

impl Double for i32
{
    fn double(&self) -> Self
    {
        self*2
    }
}

impl Double for i64
{
    fn double(&self) -> Self
    {
        self*2
    }
}



struct Fruit <T>
{
    apples: T,
    bananas: T,
}



impl <T: Double> Double for Fruit <T>
{
    fn double (&self) -> Self
    {
        Fruit
        {
            apples: self.apples.double(),
            bananas: self.apples.double(),
        }
    }
    
}

you should do as the compiler suggests and remove the () after apples

3 Likes

yes, yes. thank you

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.