Rustlang book 14.3 - error[E0425]: cannot find function `add_one` in crate `add_one`

Viewed 911

I'm working through the official Rustlang book and have reached chapter 14.3. However, once I reach a certain point of building the workspace, the compiler throws an error. My project looks like this (as per the book)

├── Cargo.lock
├── Cargo.toml
├── add-one
│   ├── Cargo.toml
│   └── src
│       └── lib.rs
├── adder
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── target

with Cargo.toml

[workspace]

members = [
    "adder",
    "add-one",
]

add-one/src/lib.rs

#![allow(unused)]
fn main() {
pub fn add_one(x: i32) -> i32 {
    x + 1
}
}

adder/Cargo.toml

...
[dependencies]

add-one = { path = "../add-one" }

adder/src/main.rs

use add_one;

fn main() {
    let num = 10;
    println!(
        "Hello, world! {} plus one is {}!",
        num,
        add_one::add_one(num)
    );
}

I initially tried typing the files out, but got the above error, so decided to copy/paste all the files from the book, but no luck there either. What am I missing? Is there a problem with my code, or is the example in the book faulty?

1 Answers

You are defining add_one inside the main function:

#![allow(unused)]
fn main() {
    pub fn add_one(x: i32) -> i32 {
        x + 1
    }
}

Nested functions are limited in scope to their parent, meaning that add_one is not visible outside of the main. You can fix this by declaring add_one in module scope:

pub fn add_one(x: i32) -> i32 {
    x + 1
}
Related