string - 获取字符串作为格式化输出中的值

标签 string pointers rust borrowing

我正在尝试通过 Rust by Example website 上的“元组类(class)” ,但我坚持格式化输出实现。我有这段代码,它打印传递的矩阵:

#[derive(Debug)]
struct Matrix{
  data: Vec<Vec<f64>>   // [[...], [...],] 
}

impl fmt::Display for Matrix {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let output_data = self.data
            // [[1, 2], [2, 3]] -> ["1, 2", "2, 3"]
            .into_iter()
            .map(|row| {
                row.into_iter()
                    .map(|value| value.to_string())
                    .collect::<Vec<String>>()
                    .join(", ")
            })
            .collect::<Vec<String>>()
            // ["1, 2", "2, 3"] -> ["(1, 2)", "(2, 3)"]
            .into_iter()
            .map(|string_row| { format!("({})", string_row) })
            // ["(1, 2)", "(2, 3)"] -> "(1, 2),\n(2, 3)"
            .collect::<Vec<String>>()
            .join(",\n");
        write!(f, "{}", output_data)
    }
}

但是编译器打印下一条消息:

<anon>:21:40: 21:44 error: cannot move out of borrowed content [E0507]
<anon>:21         let output_data = self.data
                                    ^~~~
<anon>:21:40: 21:44 help: see the detailed explanation for E0507
error: aborting due to previous error
playpen: application terminated with error code 101

我试图将 output_data 的结果包装到 RefCell 中,但编译器仍然打印此错误。我该如何解决这个问题,以便 write! 宏正常工作?

最佳答案

问题是 into_inter 获取了 data 的所有权,也就是说,从 self 中移出了 data >,这是不允许的(这就是错误所说的)。要在不获取所有权的情况下迭代向量,请使用 iter 方法:

fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    let output_data = self.data
        // [[1, 2], [2, 3]] -> ["1, 2", "2, 3"]
        .iter()
        .map(|row| {
            row.into_iter()
                .map(|value| value.to_string())
                .collect::<Vec<String>>()
                .join(", ")
        })
        .collect::<Vec<String>>()
        // ["1, 2", "2, 3"] -> ["(1, 2)", "(2, 3)"]
        .into_iter()
        .map(|string_row| { format!("({})", string_row) })
        // ["(1, 2)", "(2, 3)"] -> "(1, 2),\n(2, 3)"
        .collect::<Vec<String>>()
        .join(",\n");
    write!(f, "{}", output_data)
}

看看Formatter .它有一些方法可以帮助编写fmt。这是一个不分配中介向量和字符串的版本:

fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    let mut sep = "";
    for line in &self.data { // this is like: for line in self.data.iter()
        try!(f.write_str(sep));
        let mut d = f.debug_tuple("");
        for row in line {
            d.field(row);
        }
        try!(d.finish());
        sep = ",\n";
    }
    Ok(())
}

关于string - 获取字符串作为格式化输出中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37183823/

相关文章:

C 编程 - 限制用户输入一定数量的字符

c++ - 确定字符串是否仅包含字母数字字符(或空格)

c++ - 混合 cin 和 getline 输入问题

string - 如何将货币字符串转换为数值?

c - 为什么不能将二维数组作为函数参数传递?

rust - 如何摆脱 “cannot return value referencing temporary value”错误

types - 如何打印出一个变量及其所有(嵌套)类型信息?

python - 用于指向类的指针的 STL 映射的 SWIG 类型映射

c - 尽管使用数组的字符,但指向整数的指针不兼容

rust - 如何在 Rust 中使用串口?