在另一个结构中,您如何获得输入以从用户输入中分配结构值?

发布于 2025-02-09 02:19:40 字数 408 浏览 2 评论 0原文

我正在做一个数字猜测的游戏,猜测最接近的胜利的球员。

struct Player {
    name: String,
    balance: i32,
    betamount: i32,
    guess: i32
}

struct Game {
    p1: Player,
    p2: Player,
    random_card: i32
}

impl Game {
    pub fn start(&mut self) {
        //start function
    }
}

我如何在p1p2 start> start函数中分配name属性?这允许吗?

I am making a number guessing game, where the player who guesses the closest wins.

struct Player {
    name: String,
    balance: i32,
    betamount: i32,
    guess: i32
}

struct Game {
    p1: Player,
    p2: Player,
    random_card: i32
}

impl Game {
    pub fn start(&mut self) {
        //start function
    }
}

How I can assign the name attribute of p1 and p2 inside the start function? Is this allowed?

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

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

发布评论

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

评论(1

梦在夏天 2025-02-16 02:19:40

使用内部可突变模式。

use std::cell::RefCell;

struct Player {
name: RefCell<String>,
balance: i32,
betamount: i32,
guess: i32
}

struct Game {
    p1: Player,
    p2: Player,
    random_card: i32
}

impl Game {
    pub fn start(&mut self) {
        //start function
       
        self.p1.name.replace_with(|_|"c".to_string());
        self.p2.name.replace_with(|_|"c".to_string());
        println!("{}",self.p1.name.borrow_mut())
    }
}

fn main() {
  let mut game = Game{
      p1: Player {
          name: RefCell::new("a".to_string()),
          balance: 0,
          betamount: 0,
          guess: 0
      },
      p2: Player {
          name: RefCell::new("b".to_string()),
          balance: 0,
          betamount: 0,
          guess: 0
      },
      random_card: 0
  };
    game.start();
}

玩家对象是不可变的,但是如果我们想突变它们的字段,我们可以将它们(字段)包裹在refcell或cell中。

Use the interior mutability pattern.

use std::cell::RefCell;

struct Player {
name: RefCell<String>,
balance: i32,
betamount: i32,
guess: i32
}

struct Game {
    p1: Player,
    p2: Player,
    random_card: i32
}

impl Game {
    pub fn start(&mut self) {
        //start function
       
        self.p1.name.replace_with(|_|"c".to_string());
        self.p2.name.replace_with(|_|"c".to_string());
        println!("{}",self.p1.name.borrow_mut())
    }
}

fn main() {
  let mut game = Game{
      p1: Player {
          name: RefCell::new("a".to_string()),
          balance: 0,
          betamount: 0,
          guess: 0
      },
      p2: Player {
          name: RefCell::new("b".to_string()),
          balance: 0,
          betamount: 0,
          guess: 0
      },
      random_card: 0
  };
    game.start();
}

Player objects are immutable, but if we want to mutate their fields, we can wrap them (the fields) in RefCell or Cell.

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