[英]Why assign a reference to a struct in go?
I'm having a look at the code at this page: 我正在查看此页面上的代码:
http://golang.org/pkg/net/http/ http://golang.org/pkg/net/http/
And there's one thing I don't understand - at some point, a new structure is created and initialized like this: 有一件事我不明白 - 在某些时候,新的结构被创建并初始化如下:
client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
Why use &
when creating this structure? 为什么在创建这个结构时使用&
?
I've also read this blog post and structs are initialized like this: 我也阅读了这篇博文 ,结构体初始化如下:
r := Rectangle{}
What is the difference between both and how should I know which one to use? 两者之间有什么区别?如何知道使用哪一个?
The difference is in the type of your variable. 不同之处在于变量的类型。
client := &http.Client{
makes client
of type *http.Client
使client
类型为*http.Client
while 而
client := http.Client{
builds a http.Client
. 构建一个http.Client
。
The top one is returning a pointer. 最上面一个是返回一个指针。 It is a Go idiom instead of using new. 这是一个Go成语而不是使用new。 The second one is just a value object. 第二个只是一个价值对象。 If you need a pointer use the top. 如果你需要一个指针使用顶部。
Check the effective go doc for more about this 查看有效的go doc以获取更多相关信息
http://golang.org/doc/effective_go.html#allocation_new http://golang.org/doc/effective_go.html#allocation_new
In object-oriented programming, in order for an object to have dynamic lifetime (ie not tied to the current function call), it needs to be dynamically allocated in a place other than the current stack frame, thus you manipulate the object through a pointer. 在面向对象的编程中,为了使对象具有动态生命周期(即不依赖于当前函数调用),需要在当前堆栈帧以外的位置动态分配,因此通过指针操作对象。 This is such a common pattern that in many object-oriented languages, including Java, Python, Ruby, Objective-C, Smalltalk, JavaScript, and others, you can only deal with pointers to objects, never with an "object as a value" itself. 这是一种常见的模式,在许多面向对象的语言中,包括Java,Python,Ruby,Objective-C,Smalltalk,JavaScript等,你只能处理指向对象的指针,从不使用“对象作为值”本身。 (Some languages though, like C++, do allow you to have "objects as values"; it comes with the RAII idiom which adds some complexity.) (有些语言,比如C ++,确实允许你将“对象作为值”;它带有RAII习语,增加了一些复杂性。)
Go is not an object-oriented language, but its ability to define custom types and define methods that operates on that custom type, can be made to work very much like classes and methods. Go不是面向对象的语言,但它能够定义自定义类型并定义在该自定义类型上运行的方法,可以使其非常类似于类和方法。 Returning a pointer to the type from the "constructor" function allows the "object" to have a dynamic lifetime. 从“构造函数”函数返回指向该类型的指针允许“对象”具有动态生命周期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.