我正在玩纸牌游戏,想画一张纸牌。我有一个random_choice()
函数,它会随机选择一个i32
并将其用作切片。它没有执行预期的操作,而是说切片必须是usize
。
我尝试将i32
转换为u16
,然后转换为usize
,但是那也不起作用。我还尝试将i32
直接转换为usize
。
这些是我的数据集的结构:
struct Card {
Attack: i32,
Defense: i32,
Cost: i32,
Pay: i32,
Name: String,
Type: String,
Effect: String,
}
struct Deck {
Cards: Vec<Card>,
}
以下是功能:
fn random_choice_deck(deck: Deck) -> Card {
let slice = rand::thread_rng().gen_range(i32::from(0), i32::from(deck.Cards.len()));
return deck.Cards[usize::from(u16::from(slice))];
}
fn Draw_Cards(deck: Deck) {
let cards = vec![
random_choice(deck),
random_choice(deck),
random_choice(deck),
];
for a in cards {
println!(
"{} : C{}, A{}, D{}, P{}",
a.Name, a.Cost, a.Attack, a.Defense, a.Pay
);
}
}
输出应该是套牌中的东西。例如,我有自己的飞机甲板:
Cards: vec![
wildcat, wildcat, wildcat, wildcat, zero, zero, zero, flying_gun, flying_gun,
]
里面的东西:
let mut wildcat = Card {
Attack: i32::from(10),
Defense: i32::from(50),
Name: String::from("Wildcat"),
Type: String::from("Air"),
Effect: String::from("None"),
Cost: i32::from(25),
Pay: i32::from(50),
};
let mut zero = Card {
Attack: i32::from(20),
Defense: i32::from(35),
Name: String::from("A6M Zero"),
Type: String::from("Air"),
Effect: String::from("Air only"),
Cost: i32::from(25),
Pay: i32::from(50),
};
let mut flying_gun = Card {
Attack: i32::from(5),
Defense: i32::from(1),
Name: String::from("Flying Gun"),
Type: String::from("Air"),
Effect: String::from("None"),
Cost: i32::from(5),
Pay: i32::from(5),
};
它应该输出wildcat
,zero
或flying_gun
,但它会输出以下错误:
error[E0277]: the trait bound `u16: std::convert::From<i32>` is not satisfied
return deck.Cards[usize::from(u16::from(slice))
^^^^^^^^^ the trait 'std::convert::From<i32>' is not implemented for 'u16'