【问题标题】:How to use multiparameter String functions in Rust?如何在 Rust 中使用多参数字符串函数?
【发布时间】:2018-09-04 03:00:16
【问题描述】:

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

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

【问题讨论】:

  • 在 rust 中,没有可变参数函数,所以你正在做的事情是行不通的。您只能将宏用于不特定数量的参数,例如 format!println!write!(它们都将回退到 format!

标签: function oop rust parameter-passing variadic-functions


【解决方案1】:

您可能打算使用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 trait,它定义了一个接受单个参数的 from 方法(因此错误消息中的“此函数接受 1 个参数”)。

format! 已经生成了String,因此无需转换。

【讨论】:

    猜你喜欢
    • 2021-04-23
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多