如何在生锈中多次使用变量?

发布于 2025-01-20 15:23:28 字数 259 浏览 2 评论 0原文

我知道Rust中借贷和拥有的基本原则。 但是,我找不到解决以下情况的方法:

fn create_user(full_name: String) -> User {
  User {
    field1: full_name,
    field2: full_name,
  }
}

如果我想在上面的示例中将几个字段引用给给定参数怎么办?使用“*”不能解决问题,也没有编译。

在询问之前,我真的没有找到这个问题的答案。

I know about the basic principles of borrowing and owning in Rust.
However, I can't find a way to solve the following situation:

fn create_user(full_name: String) -> User {
  User {
    field1: full_name,
    field2: full_name,
  }
}

What if I would like to reference couple of fields in the example above to the given argument? Using of the "*" doesn't solve the problem and is not compiling.

I really did not find an answer to this question for a while before asking.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鲜血染红嫁衣 2025-01-27 15:23:28

有一些选项,包括(可能不仅):

如果tclone

fn create_user(full_name: T) -> User where T: Clone {
  User {
    field1: full_name.clone(),
    field2: full_name.clone(),
  }
}

如果t不是clone> clone,您可以利用field2作为返回参考的方法:

struct User {
   field1: T
}

impl User {
    pub fn field2(&self) -> &T {
        &self.field1
    }
}

fn create_user(full_name: T) -> User {
  User {
    field1: full_name,
  }
}

There are a few options, including (and probably not only):

If T is Clone

fn create_user(full_name: T) -> User where T: Clone {
  User {
    field1: full_name.clone(),
    field2: full_name.clone(),
  }
}

if T is not Clone, you could leverage field2 as a method returning a reference:

struct User {
   field1: T
}

impl User {
    pub fn field2(&self) -> &T {
        &self.field1
    }
}

fn create_user(full_name: T) -> User {
  User {
    field1: full_name,
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文