ArekBulski
ArekBulski

Reputation: 5118

Rust: no method named `join` found for struct `std::string::String`

Hmm why is this not working?

let numcities = 40;
let mut file = std::fs::File::create(args[3].clone()).unwrap();

file.write((0..numcities).map(|i| i.to_string()).collect::<String>().join("->")).unwrap();

Compilation error:

error[E0599]: no method named `join` found for struct `std::string::String` in the current scope
  --> main.rs:42:72
   |
42 |         file.write((0..numcities).map(|i| i.to_string()).collect::<String>().join("->")).unwrap();
   |                                                                              ^^^^ method not found in `std::string::String`

Upvotes: 2

Views: 4888

Answers (1)

Netwave
Netwave

Reputation: 42756

You need to collect into an intermediary Vec<String>:

let data = ["A", "B", "C"];
let result = data.iter().map(|s| s.to_string()).collect::<Vec<String>>().join("->"));

In nightly 1.53, you can use intersperse for example:

#![feature(iter_intersperse)]

fn main() {
    let data = vec!["A", "B", "C"];
    let result = data
        .iter()
        .map(|x| x.to_string())
        .intersperse("->".to_string())
        .collect::<String>();
    println!("{}", result);
}

Playground

Upvotes: 2

Related Questions