Dialvive
Dialvive

Reputation: 386

How to use multiparameter String functions in Rust?

I want to make a to_string() fn in Rust with &self as parameter, and calling the references of the elements of &self inside the function:

//! # Messages
//!
//! Module that builds and returns messages with user and time stamps.

use time::{Tm};

/// Represents a simple text message.
pub struct SimpleMessage<'a, 'b> {
    pub moment: Tm,
    pub content: &'b str,
}

impl<'a, 'b> SimpleMessage<'a, 'b> {

    /// Gets the elements of a Message and transforms them into a String.
    pub fn to_str(&self) -> String {
        let mut message_string =
            String::from("{}/{}/{}-{}:{} => {}",
                         &self.moment.tm_mday,
                         &self.moment.tm_mon,
                         &self.moment.tm_year,
                         &self.moment.tm_min,
                         &self.moment.tm_hour,
                         &self.content);
        return message_string;
    }
}

But $ cargo run returns:

    error[E0061]: this function takes 1 parameter but 8 parameters were supplied
      --> src/messages.rs:70:13
       |
    70 | /             String::from("{}/{}/{}-{}:{}, {}: {}",
    71 | |                          s.moment.tm_mday,
    72 | |                          s.moment.tm_mon,
    73 | |                          s.moment.tm_year,
    ...  |
    76 | |                          s.user.get_nick(),
    77 | |                          s.content);
       | |___________________________________^ expected 1 parameter

I really don't understand the problem of this syntax, what am I missing?

Upvotes: 0

Views: 102

Answers (1)

Francis Gagn&#233;
Francis Gagn&#233;

Reputation: 65782

You probably meant to use the format! macro:

impl<'b> SimpleMessage<'b> {
    /// Gets the elements of a Message and transforms them into a String.
    pub fn to_str(&self) -> String {
        let message_string =
            format!("{}/{}/{}-{}:{} => {}",
                         &self.moment.tm_mday,
                         &self.moment.tm_mon,
                         &self.moment.tm_year,
                         &self.moment.tm_min,
                         &self.moment.tm_hour,
                         &self.content);
        return message_string;
    }
}

String::from comes from the From trait, which defines a from method that takes a single parameter (hence "this function takes 1 parameter" in the error message).

format! already produces a String, so no conversion is necessary.

Upvotes: 3

Related Questions