dsljpwi494719 2014-07-08 15:24
浏览 66
已采纳

golang具有指针的指针还是指针的引用功能?

Hi everyone in Golang what will you do if you need to change the pointer (change where the pointer points to rather than change the value where this pointer points to). I know it is really easy in C++ by using reference, like"

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

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

Or equivalently in C, use pointer's pointer:

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

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

I wonder if Golang has this neat feature, or if not, the only way is to set at function's return?

  • 写回答

1条回答 默认 最新

  • doutang8098 2014-07-08 15:28
    关注

    You can use a pointer to a pointer, just like in 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
    ", ptr)
        myFunc(&ptr) // ptr is moved
        fmt.Printf("%p
    ", ptr)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了