golang从函数返回对象

Tom*_*Tom 4 c go

当我从go中的函数返回一个新对象时,我正在努力弄清楚到底发生了什么.

我有这个

func createPointerToInt() *int {
    i := new(int)
    fmt.Println(&i);
    return i;
}

func main() {
    i := createPointerToInt();
    fmt.Println(&i);
}
Run Code Online (Sandbox Code Playgroud)

返回的值是

0x1040a128
0x1040a120
Run Code Online (Sandbox Code Playgroud)

我希望这两个值是相同的.我不明白为什么有8字节的差异.

在我所看到的等效C代码中:

int* createPointerToInt() {
    int* i = new int;
    printf("%#08x\n", i);
    return i;
}

int main() {
    int* r = createPointerToInt();
    printf("%#08x\n", r);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

返回的地址是相同的:

0x8218008
0x8218008
Run Code Online (Sandbox Code Playgroud)

我在这里错过了一些令人目眩的事吗?任何澄清将不胜感激!

Sad*_*que 7

您正在此处打印指针的地址fmt.Println(&i);.试试这个:

func main() {
    i := createPointerToInt();
    fmt.Println(i); //--> Remove the ampersand
}
Run Code Online (Sandbox Code Playgroud)

i返回的指针是createPointerToInt- &i您是要尝试打印的指针的地址.请注意您的C示例中正确打印它:

printf("%#08x\n", r);
                 ^No ampersand here
Run Code Online (Sandbox Code Playgroud)