【问题标题】:Return a Formatted String in Rust在 Rust 中返回一个格式化的字符串
【发布时间】:2020-12-15 14:39:49
【问题描述】:

我想创建一个函数,它接受xy 坐标值并返回格式为(x,y) 的字符串:

pub struct Coord {
    x: i32,
    y: i32,
}

fn main() {
    let my_coord = Coord {
        x: 10,
        y: 12
    };

    let my_string = coords(my_coord.x, my_coord.y);

    fn coords(x: i32, y: i32) -> &str{
        let l = vec!["(", x.to_string(), ",", y.to_string(), ")"];
        let j = l.join("");
        println!("{}", j);
        return &j
    }
}

这给了我错误:

   |
14 |     fn coords(x: i32, y: i32) -> &str {
   |                                  ^ expected named lifetime parameter
   |
   = help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments
help: consider using the `'static` lifetime
   |

添加'static 生命周期似乎会导致此函数出现许多其他问题?我该如何解决这个问题?

【问题讨论】:

  • 返回一个字符串。
  • 有个有用的format!宏。

标签: string rust formatting lifetime borrow-checker


【解决方案1】:

更惯用的方法是为您的类型 Coord 实现 Display 特征,这将允许您直接在其上调用 to_string(),并且还允许您直接在 println! 宏中使用它.示例:

use std::fmt::{Display, Formatter, Result};

pub struct Coord {
    x: i32,
    y: i32,
}

impl Display for Coord {
    fn fmt(&self, f: &mut Formatter) -> Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

fn main() {
    let my_coord = Coord { x: 10, y: 12 };
    
    // create string by calling to_string()
    let my_string = my_coord.to_string();
    println!("{}", my_string); // prints "(10, 12)"
    
    // can now also directly pass to println! macro
    println!("{}", my_coord); // prints "(10, 12)"
}

playground

【讨论】:

    【解决方案2】:

    您尝试做的事情是不可能的。您正在创建的 String 是函数的本地地址,并且您正在尝试返回对它的引用。

    j 将被丢弃在函数的末尾,因此您无法返回对它的引用。

    您必须返回String

    fn coords(x: i32, y: i32) -> String {
        let l = vec![
            "(".into(),
            x.to_string(),
            ",".into(),
            y.to_string(),
            ")".into(),
        ];
        let j = l.join("");
        println!("{}", j);
        return j;
    }
    

    Playground


    更好的方法:

    fn coords(x: i32, y: i32) -> String {
        let x = format!("({},{})", x, y);
        println!("{}", x);
        return x;
    }
    

    Playground

    【讨论】:

      【解决方案3】:

      这最终对我有用:

      
      pub struct Coord{
          x: i32,
          y: i32,
      }
      
      fn main(){
          let my_coord = Coord{
              x: 10,
              y: 12
          };
      
          let my_string = coords(my_coord.x, my_coord.y);
      
          fn coords(x: i32, y: i32) -> String{
              let myx = x.to_string(); 
              let myy = y.to_string(); 
              let l = vec!["(", &myx, ",", &myy, ")"];
              let j = l.join("");
              return j; 
          }
      }
      

      【讨论】:

      • 你可以直接返回format!("({}, {})", x, y),这样更简单、更易读、启动更高效。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 2014-05-23
      • 2018-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      相关资源
      最近更新 更多