2014-07-08 70 views
-2

大家好,如果你需要改变指针(改变指针指向的位置而不是改变指针指向的值),你会怎么做?我知道这是在C++中使用的参考真的很容易,像”golang有指针的指针或指针的参考特征?

void myFunc(Type*& ptr) 
{ 
    ptr = anotherPointer; 
} 

int main 
{ 
    Type* ptr = &someValue; 
    myFunc(ptr); // ptr is moved 
} 

或等价于C,使用指针的指针:

void myFunc(Type** ptrsptr) 
{ 
    *ptrsptr = anotherPointer; 
} 

int main 
{ 
    Type* ptr = &someValue; 
    myFunc(&ptr); // ptr is moved 
} 

不知Golang有这个实用的功能,如果还是不行,唯一的办法是设置在函数的返回?

回答

4

您可以在C

http://play.golang.org/p/vE-3otpKkb

使用指针的指针,就像
package main 

import "fmt" 

type Type struct{} 

var anotherPointer = &Type{} 

func myFunc(ptrsptr **Type) { 
    *ptrsptr = anotherPointer 
} 

func main() { 
    ptr := &Type{} 
    fmt.Printf("%p\n", ptr) 
    myFunc(&ptr) // ptr is moved 
    fmt.Printf("%p\n", ptr) 
} 
+0

很好的答案!但为什么golang不采用C++风格的引用? – Jun

+0

@Jun - 因为Go不是C++。 Go力求简单,正交的语言特性。 – JimB