读后感 这个 的文章,我心中有一些疑问。
基本上,为什么我们需要存储返回值的 append()
在围棋中?这个函数究竟是如何实现的?
我曾试图在C语言(如果我没有弄错的话,C语言是第一个用来实现Go语言的语言)中复制(某种程度上)append的机制。我使用了 malloc()
而不是一个数组,因为在函数返回后,它不会重新分配片断。
这是我的代码。
#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;
}
(我省略了NULLs检查,只显示与问题相关的部分).
如果我在使用这段代码,我可以使用 append()
而不需要存储它的返回值,也不需要创建一个新的分片头。
那么如何实现 append()
函数,使得它需要存储一个新的分片头?即使 zerothElement
使用数组,是不是意味着它只需要改变数组而不是整个片头?
我在这里遗漏了什么?
谢谢 :)
基本上,为什么我们需要在Go中存储append()的返回值?
只有当你打算使用带有附加值的分片时才需要存储这个值。
这个函数到底是如何实现的呢?
Go是开源的,查阅源码即可。(顺便说一句:这个没意思。)