Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust struct impl method wants struct as argument

I don’t understand, what I am supposed to do here.

I have this rust struct with implementation:

use std::io;
use std::fs::File;
use std::io::Read;
use serde::Deserialize;

#[derive(Deserialize, Debug)]
pub struct TemplateLoader {
  pub template: String,
  pub template_path: String
}

impl TemplateLoader {

  pub fn load_template_file(&self) -> Result<String, io::Error> {
    let opened_file = File::open(&self.template_path);

    let mut validated_file = match opened_file {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let mut template = String::new();

    match validated_file.read_to_string(&mut template) {
        Ok(_) => Ok(template),
        Err(e) => return Err(e),
    }     
  }

  pub fn new(&self) -> Self {

    let template_path = String::from("templates/template.hbs");
    
    let item = Self { template_path, template: String::from("") }; 
 
    let _result = self.load_template_file(); 

    item
  
  }
}

When I call it from main like so

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

use crate::utils::template_loader::TemplateLoader;  

pub fn main() {
    let template_loader = TemplateLoader::new();
}

I keep getting

                      this function takes 1 argument but 0
                      arguments were supplied (rustc E0061)
let template_loader = TemplateLoader::new();
                      ^^^^^^^^^^^^^^^^^^^-- an argument of type `&TemplateLoader` is missing.

I don’t understand that error message. Why does the compiler want an argument of type TemplateLoader for the ::new method, when there is none defined in the method signature?

All there is, is the &self argument, which is passed by Rust anyway.

>Solution :

A new() method shouldn’t take in a reference to self since it doesn’t exist yet. It looks like you need to remove that and then call item.load_template_file or Self.load_template_file(&item)/Self::load_template_file(&item) (i don’t remember if Rust uses . or :: for this).

new is a method of the class, not of the instances

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading