登录
首页 >  Golang >  Go问答

Go 中的append 相当于 Rust 中的什么?

来源:stackoverflow

时间:2024-02-07 07:46:04 277浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《Go 中的append 相当于 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"
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>