公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:51998
  • 待审:31
  • 小程序:12
  • 文章:1030137
  • 会员:747

php小编西瓜在这里为大家解答一个问题:“Rust 相当于 Go 中的 append 是什么?”Rust 是一种系统级编程语言,而 Go 是一种并发编程语言。在 Rust 中,相当于 Go 中的 append 函数的功能是使用 Vec 类型的 push 方法。Vec 是 Rust 标准库中的一个动态数组类型,使用 push 方法可以在数组的末尾添加元素。这种功能类似于 Go 中的 append 函数,但是在 Rust 中需要使用 Vec 的 push 方法实现。通过这种方式,Rust 提供了一种简单而灵活的方式来操作动态数组。

问题内容

我试图通过自己阅读文档来弄清楚,但对于如何将此 go 函数转换为 rust 没有运气:

func main() {
  cards := []string{"ace of diamonds", newcard()}
  cards = append(cards, "six of spades")

  fmt.println(cards)
}

func newcard() string {
  return "five of diamonds"
}

登录后复制

这是不正确的,至少我知道的 cards.append 是错误的:

fn main() {
    let mut cards: [&str; 2] = ["Ace of Diamonds", new_card()];
    let mut additional_card: [&str; 1] = ["Six of Spades"];
    cards.append(additional_card);

    println!("cards")
}

fn new_card() -> &'static str  {
    "Five of Diamonds"
}

登录后复制

解决方法

你不能。就像在 go 中一样,rust 数组是固定大小的。

类型 [&str; 2]rust 中的 大致相当于 go 中的 [2]string,但你也不能对其进行 append 。

在 rust 中,最接近 go 切片的是 vec 您可以像这样使用:

fn main() {
    let mut cards = vec!["Ace of Diamonds", new_card()];
    let additional_cards: [&str; 2] = ["Six of Spades", "Seven of Clubs"];
    // for anything that implements `IntoIterator` of cards
    cards.extend(additional_cards);
    // or for a single card only
    cards.push("Three of Hearts");

    println!("{cards:?}")
}

fn new_card() -> &'static str {
    "Five of Diamonds"
}

登录后复制

分享到:
标签:标准库
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 51998

    网站

  • 12

    小程序

  • 1030137

    文章

  • 747

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定