如何在定义它们的作用域之外引用指向相同结构对象的指针?

huangapple go评论70阅读模式
英文:

How to reference pointers to the same struct object from outside the scope in which they were defined

问题

在下面的代码中,两个指针变量 r1r2(类型为 *Rect)引用了同一个结构体对象(类型为 Rect):

type Rect struct {
	width int
}

func main() {
	r1 := new(Rect)
	r2 := new(Rect)
	r1 = r2

	fmt.Printf("%p, %p", r1, r2) // 打印每个变量指向的 Rect 的地址
}

0xc00001c038, 0xc00001c038 (正确的输出)

如何在定义它们的函数之外将 r1r2 引用到同一个结构体对象?换句话说,如何创建一个函数来替代 r1 = r2?我尝试在外部函数中对变量进行解引用并赋值,但未能成功将 r1 引用到 r2 的引用的结构体对象:

func assign(r1, r2 *Rect) {
	*r1 = *r2
}

func main() {
	r1 := new(Rect)
	r2 := new(Rect)
	assign(r1, r2)

	fmt.Printf("%p, %p", r1, r2) // 打印每个变量指向的 Rect 的地址
}

0xc00001c030, 0xc00001c038 (错误的输出)

PLAYGROUND: https://go.dev/play/p/ld0C5Bkmxo3

英文:

In the below code, two pointer variables, r1 and r2 (of type *Rect), reference the same struct object (of type Rect):

type Rect struct {
	width int
}

func main() {
	r1 := new(Rect)
	r2 := new(Rect)
	r1 = r2

	fmt.Printf("%p, %p", r1, r2) // prints the addresses of the Rects being pointed to by each variable
}

0xc00001c038, 0xc00001c038 (GOOD OUTPUT)

How would you reference r1 and r2 to the same struct object from outside of the function in which they were defined? In other words, how would you create a function to replace r1 = r2? My attempt at dereferencing and then assigning the variables from within an external function did not succeed at referencing r1 to r2's referenced struct object:

func assign(r1, r2 *Rect) {
	*r1 = *r2
}

func main() {
	r1 := new(Rect)
	r2 := new(Rect)
	assign(r1, r2)

	fmt.Printf("%p, %p", r1, r2) // prints the addresses of the Rects being pointed to by each variable
}

0xc00001c030, 0xc00001c038 (BAD OUTPUT)

PLAYGROUND: https://go.dev/play/p/ld0C5Bkmxo3

答案1

得分: 1

如果你需要在函数内部改变指针所指向的位置,你需要传递它的地址:

func assign(r1, r2 **Rect) {
	*r1 = *r2
}

func main() {
	r1 := new(Rect)
	r2 := new(Rect)
	assign(&r1, &r2)

	fmt.Printf("%p, %p", r1, r2) // 打印每个变量所指向的 Rect 的地址
}

PLAYGROUND: https://go.dev/play/p/5fAakjB50JJ

英文:

If you need to change where a pointer points to within a function, you have to pass the address of it:

func assign(r1, r2 **Rect) {
	*r1 = *r2
}

func main() {
	r1 := new(Rect)
	r2 := new(Rect)
	assign(&r1, &r2)

	fmt.Printf("%p, %p", r1, r2) // prints the addresses of the Rects being pointed to by each variable
}

PLAYGROUND: https://go.dev/play/p/5fAakjB50JJ

huangapple
  • 本文由 发表于 2022年10月6日 12:31:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/73968687.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定