Как использовать многопараметрические функции String в Rust? - PullRequest
0 голосов
/ 04 сентября 2018

Я хочу сделать to_string() fn в Rust с &self в качестве параметра и вызывать ссылки на элементы &self внутри функции:

//! # 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;
    }
}

Но $ cargo run возвращает:

    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

Я действительно не понимаю проблемы этого синтаксиса, что мне не хватает?

1 Ответ

0 голосов
/ 04 сентября 2018

Вы, вероятно, хотели использовать макрос format!:

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 происходит от черты From, которая определяет метод from, который принимает один параметр (следовательно, «эта функция принимает 1 параметр» в сообщении об ошибке).

format! уже производит String, поэтому преобразование не требуется.

...