看完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/