John164
John164

Reputation: 149

Can't find method in module

I am learning Rust and trying to figure out why I can't call a method from a module I have written. The code is very simple as it's a learning exercise and I have read this and this but I still don't know what the problem is. I have also tried using the code from this question almost exactly however the error persists.

The code for main.rs and helper.rs are below.

main.rs:

mod helpers;

fn main() {
    let h = helpers::new("TestString");
    println!("{}", h.get_name().to_string());
    helpers::test_func();
}

helpers.rs

struct Helper{
    name: String
}

impl Helper {
    pub fn new(name: &String) -> Helper {
        let helper = Helper{ name: name.to_string()};
        return helper;
    }
}

impl Helper {
    pub fn get_name(&self) -> &String {
        return &self.name;
    }
}

pub fn test_func(){
    println!("test_func was called.");
}

The error I am getting is:

error[E0425]: cannot find function `new` in module `helpers`
 --> src/main.rs:4:30
  |
4 |     let h = helpers::new("TestString");
  |                              ^^^ not found in `helpers`

error: aborting due to previous error

I know the file is being read because if you commend out lines 4 & 5 from main.rs and just run helpers::test_func() it works fine however I don't know why it can't find the new method.

Any help would be very much appreciated.

Upvotes: 1

Views: 2630

Answers (2)

pigeonhands
pigeonhands

Reputation: 3424

First thing is the Helper struct needs to be exposed from the module. You can do this with the pub keyword.

pub struct Helper { ...

The other thing is that helpers is the name of the module, but the new method is associated with the Helper struct. You can import the struct with

mod helpers;
use helpers::Helper;

and then call it with

Helper::new(&String::from(""))

side note: You can change the parameter type on new from &String to &strto avoid having to make a new String object and saving a pointless copy.

pub fn new(name: &str) -> Helper {
    Helper{ 
        name: name.to_string()
    }
}

then call it with

Helper::new("")

Upvotes: 5

Doruk Eren Aktaş
Doruk Eren Aktaş

Reputation: 2337

The error is constructor call. When calling constructors in rust you can use this syntax:

let h = Helper{ name: "TestString".to_string() };

Also you need to use to_string method to convert &str to String.

Upvotes: 0

Related Questions