Calling impl functions from another impl function?

In this cut down example I have been

  • calling an impl new to create a new stuct instance
  • the new function attempts to call another impl function

So far no matter the combination of self or other hacks on my part the compiler cannot see the other impl function and gives error:

error: unresolved name "other_method"

use std::os;
use std::env;
use std::collections::HashMap;
use std::ffi::OsString;


pub struct config {
	transport : String,
	hostname : String,
	output : String,
	os_config  :  HashMap< String, OsString>
}

impl config {
  fn new() -> config {
	  let mut localConfig = config{ transport : "http".to_string(), hostname: "".to_string(),
	  output :  "".to_string(),
	  os_config : HashMap::new() };
	  other_method();  /// <-- trying to call another impl method 
	  return localConfig;
  }

// the function I cannot access?
  fn other_method() {
      println! ("running other method" );
  }

}

fn main (){
	let myConfig  = config::new();
	println! ("working so far " );
}
1 Like

Read up on method syntax. This should help you define and call the methods correctly.

1 Like

Per Rust style, you want to upcase "Config"

As the documentation you were pointed to notes, methods without &self or self as the first variable are called through the Struct::method(); rather than the s.method() syntax. In your example (assuming Config rather than config, you'd want to call Config::other_method();

A few other things:

  1. String::from("foo") is preferred to "foo".to_string()
  2. Your localConfig doesn't need to be mut
  3. hostname and output probably want to be Option<String> and defaulted to None rather than the empty string
  4. Rust style wants an implicit return (just localConfig rather than return localConfig;) as the last line in a function that returns a value.
  5. Your transport variable probably wants to be an enum rather than a String

(Warning: following not run):

pub enum Transport {
    Http,
    Foo,
    Bar
}

pub struct Config {
    transport: Tranport,
    hostname: Option<String>,
    output: Option<String>
    os_config: HashMap<String,OsString>
}

impl Config {
    fn new() -> Self {
        Config::other_method();
        Config { transport: Transport::Http, hostname: None, output: None, os_config: HashMap::new()}
    }
    
    fn other_method() {
        println!("in other method");
    }
}

You can also call via Self:

struct Config;

impl Config {
    fn call_twice() {
        Self::other();
        Config::other();
    }
    fn other() { println! ("works" ) }
}

fn main (){
    Config::call_twice();
}

playpen

1 Like