Go:函数返回指向内存的指针

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

Go: function return pointer to memory

问题

我正在遵循 golang tour,这个页面:https://tour.golang.org/methods/3

package main

import (
	"fmt"
	"math"
)

type Vertex struct {
	X, Y float64
}

func (v Vertex) Scale(f float64) *Vertex {
	v.X = v.X * f
	v.Y = v.Y * f
	return &v //我返回了指向v的指针
}

func (v Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
	v := &Vertex{3, 4}
	fmt.Printf("Before scaling: %+v, Abs: %v\n", v, v.Abs())
	v = v.Scale(5) //我将其赋值给v
	fmt.Printf("After scaling: %+v, Abs: %v\n", v, v.Abs())
}

当我调用 v.Scale 时,v 的一个副本被传递给 Scale 函数。然后,Scale 函数返回一个指向它接收到的 v 的指针。

这样安全吗?或者我会在某个时候遇到 sigsev 错误吗?

(对不起,标题不太合适,但我想不到一个合适的,请随意编辑)

英文:

I'm following the golang tour, this page: https://tour.golang.org/methods/3

package main

import (
	"fmt"
	"math"
)

type Vertex struct {
	X, Y float64
}

func (v Vertex) Scale(f float64) *Vertex {
	v.X = v.X * f
	v.Y = v.Y * f
	return &v //I'm returning a pointer to v
}

func (v Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
	v := &Vertex{3, 4}
	fmt.Printf("Before scaling: %+v, Abs: %v\n", v, v.Abs())
	v = v.Scale(5) //I'm assiging it to v
	fmt.Printf("After scaling: %+v, Abs: %v\n", v, v.Abs())
}

When i call v.Scale a copy of v is passed to the Scale function. Then, the Scale returns a pointer to the v that it has recevied.

Is this safe? Or will i end up with a sigsev at some point?

(Sorry for the title, but i couldn't think of a proper one feel free to edit it)

答案1

得分: 1

这是完全安全的。当你调用v.Scale时,会分配一个Vertex的副本,并返回一个指向它的指针。只要指针引用了这个副本,它就不会被垃圾回收。如果指针超出了作用域(无法再使用),那么这个副本将被释放。

英文:

That's perfectly safe. When you call v.Scale, a copy of Vertex is allocated and you return a pointer to it. The copy won't be garbage collected as long as it's referenced to by the pointer. If the pointer goes out of scope (and can't be used anymore), the copy would be freed.

huangapple
  • 本文由 发表于 2015年12月17日 18:58:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/34332873.html
匿名

发表评论

匿名网友

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

确定