Go语言append方法的Rust等价实现是什么?代码转换求助
正确的Rust实现方式
你的问题核心是混淆了Rust里固定长度数组和**动态数组(Vec)**的区别:
- Go中的
[]string是动态切片,可随时扩容;而你写的[&str; 2]是Rust的固定长度数组,大小在编译时确定,无法动态添加元素,自然没有append方法。
下面是对应Go代码的正确Rust实现:
fn main() { // 用vec!宏创建动态Vec,对应Go的动态切片 let mut cards = vec!["Ace of Diamonds", new_card()]; // 添加单个元素用push方法 cards.push("Six of Spades"); // 用{:?}格式符打印Vec的内容,而不是单纯打印字符串"cards" println!("{:?}", cards); } fn new_card() -> &'static str { "Five of Diamonds" }
补充说明:
- 如果需要批量添加多个元素,可以用
extend方法,比如:cards.extend(["Six of Spades", "Queen of Hearts"]); - 如果你后续需要修改字符串内容(比如从用户输入生成动态字符串),建议使用
Vec<String>而非Vec<&'static str>,示例:let mut cards = vec![String::from("Ace of Diamonds"), new_card_string()]; cards.push(String::from("Six of Spades")); fn new_card_string() -> String { String::from("Five of Diamonds") }
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

