如何在Rust中使用多参数字符串函数?

问题描述 投票:0回答:1

我想用to_string()作为参数在Rust中创建一个&self fn,并在函数内调用&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

我真的不明白这种语法的问题,我错过了什么?

function oop rust parameter-passing variadic-functions
1个回答
3
投票

您可能打算使用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,因此无需转换。

© www.soinside.com 2019 - 2024. All rights reserved.