大家好,Golang 中,如果您需要更改指针(更改指针指向的位置而不是更改此指针指向的值),您会怎么做?我知道在 C++ 中通过使用引用非常容易,例如“
void myFunc(Type*& ptr)
{
ptr = anotherPointer;
}
int main
{
Type* ptr = &someValue;
myFunc(ptr); // ptr is moved
}
Run Code Online (Sandbox Code Playgroud)
或者等效地在 C 中,使用指针的指针:
void myFunc(Type** ptrsptr)
{
*ptrsptr = anotherPointer;
}
int main
{
Type* ptr = &someValue;
myFunc(&ptr); // ptr is moved
}
Run Code Online (Sandbox Code Playgroud)
我想知道 Golang 是否有这个巧妙的功能,或者如果没有,唯一的方法是在函数返回时设置?
您可以使用指向指针的指针,就像在 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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
795 次 |
| 最近记录: |