英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论