为什么Golang对结构类型既有值类型又有指针类型?

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

why golang has both values and pointers for struct types

问题

Go的设计目标之一是简单。但是Go在结构体类型中既有值又有指针,我认为这对开发者来说很容易混淆,而Java和JavaScript有一个非常简单的规则:原始类型始终是值,对象类型始终是指针。为什么Go不采用Java和JavaScript的这个简单规则呢?或者说相比指针,值有哪些重要的优势呢?

英文:

One of Go's design goals is to be simple. But Go have both values and pointers for struct types which I think is confusing for developers to choose from, while java and javascript have a very simple rule: primitive types are always values, object types are always pointers. Why doesn't Go adopt this simple rule from java and javascript? Or is there any vital advantages of values compared to pointers?

答案1

得分: 2

在Go语言中,由于默认进行垃圾回收,灵活性使得你可以优化你的程序。请参考FAQ

> 在可能的情况下,Go编译器会将函数内部局部变量分配在该函数的栈帧中。然而,如果编译器无法证明变量在函数返回后不再被引用,那么编译器必须将变量分配在垃圾回收的堆上,以避免悬空指针错误。

如果一个结构体通过值返回,它不会被分配在堆上。因此,垃圾回收器不需要跟踪它来确定何时可以安全地释放为其分配的内存。

英文:

In Go, the flexibility allows you to optimize your program since it's by default garbage-collected. See the FAQ:

> When possible, the Go compilers will allocate variables that
> are local to a function in that function's stack frame. However, if
> the compiler cannot prove that the variable is not referenced after
> the function returns, then the compiler must allocate the variable on
> the garbage-collected heap to avoid dangling pointer errors.

If a struct is returned by value, it won't be allocated on the heap. Thus, the garbage collector doesn't have to keep track of it to determine when it's safe to free the memory allocated for it.

huangapple
  • 本文由 发表于 2016年1月23日 17:54:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/34962026.html
匿名

发表评论

匿名网友

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

确定