go - 在 Go 中追加的返回值

标签 go slice

看完this文章,我有一个问题。

基本上,为什么我们需要存储 append() 的返回值在围棋?该功能是如何实际实现的?

我试图在 C 中复制(某种程度)附加机制(如果我没记错的话,这是用于实现 Go 语言的第一种语言)。我用了malloc() ,而不是数组,因为它不会在函数返回后释放 slice 。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct SliceHeader {
    int length;
    int capacity;
    int *zerothElement;
} SliceHeader;

void append(SliceHeader *sh, int element)
{
    if (sh->length == sh->capacity) {
        // grow capacity size
        sh->capacity += 10;
        realloc(sh->zerothElement, sh->capacity);
    }
    sh->zerothElement[sh->length] = element;
    sh->length++;
}

SliceHeader * make(int capacity)
{
    SliceHeader *sh = (SliceHeader *) malloc(sizeof(sh));

    sh->length = 0;
    sh->capacity = capacity;
    sh->zerothElement = (int *) malloc(capacity * sizeof(int));

    return sh;
}

int main()
{
    SliceHeader *sh = make(3);

    append(sh, 5);
    append(sh, 10);
    append(sh, 15);

    append(sh, 20); // exceed the original capacity, should reallocate

    for (int i = 0; i < sh->length; i++) {
        printf("%d\n", *((sh->zerothElement)+i) );
    }

    free(sh->zerothElement);
    free(sh);

    return 0;
}

(我省略了 NULL 检查以仅显示主要问题的相关部分)。

如果我使用此代码,我可以使用 append()无需存储其返回值,也无需创建新的 slice 头。

那么 append() 的执行情况如何? Golang 中需要存储新 slice 头的函数?即使 zerothElement使用数组,这是否意味着它只需要更改数组而不是整个 slice 头?

我在这里想念什么?

谢谢 :)

最佳答案

Basically, why we need to store the return value of append() in Go?



如果您打算使用带有附加值的 slice ,则只需要存储此值。

How is the function actually implemented?



Go 是开源的,只需查阅源代码即可。 (顺便说一句:这很无趣。)

关于go - 在 Go 中追加的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62245274/

相关文章:

go - 特拉维斯 CI + 去 : creating a specific build flow for different OS

python - 选择括号中的数据

arrays - 如何在 Go 中声明数组(或等效数组)

Docker 抛出 "{binary} not found"错误

docker - 不使用operator-sdk直接构建operator镜像?

pointers - 在 Go 中将指针分配给接口(interface)时与隐式指针取消引用混淆

go - 为父 golang 结构字段赋值

python - 计数与 2 个字符串索引迭代匹配

Golang - 在结构中使用 chan slice

go - 引用未定义的标识符 bytes.ReplaceAll