Return Rust 中的格式化字符串

Return a Formatted String in Rust

我想创建一个函数,它接受 xy 坐标值以及 returns 格式为 (x,y):[=17= 的字符串]

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 生命周期似乎会导致此函数出现许多其他问题?我该如何解决这个问题?

更惯用的方法是为您的类型 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

这最终对我有用:


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; 
    }
}

你想做的事是不可能的。您正在创建的 String 是函数的局部变量,并且您正在尝试 return 对其的引用。

j 将在函数末尾删除,因此您不能 return 引用它。

你必须return一个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