英文:
Golang: How do you use a pointer on a struct that hasn't been initialized yet
问题
所以我在这里看了一下文件。
他们调用record := &accessLog,但他们从未先将其初始化为变量,如果以这种方式处理多个同时连接,是否有可能record会被其他人的数据覆盖?
type accessLog struct {
ip, method, uri, protocol, host string
elapsedTime time.Duration
}
func LogAccess(w http.ResponseWriter, req *http.Request, duration time.Duration) {
clientIP := req.RemoteAddr
if colon := strings.LastIndex(clientIP, ":"); colon != -1 {
clientIP = clientIP[:colon]
}
record := &accessLog{
ip: clientIP,
method: req.Method,
uri: req.RequestURI,
protocol: req.Proto,
host: req.Host,
elapsedTime: duration,
}
writeAccessLog(record)
}
英文:
So I was looking at the file here.
They call record := &accessLog but they don't ever Initialize it as a variable first and if they do it that way if there are multiple simultaneous connections is there a possibility record will get over written with somebody else's data?
type accessLog struct {
ip, method, uri, protocol, host string
elapsedTime time.Duration
}
func LogAccess(w http.ResponseWriter, req *http.Request, duration time.Duration) {
clientIP := req.RemoteAddr
if colon := strings.LastIndex(clientIP, ":"); colon != -1 {
clientIP = clientIP[:colon]
}
record := &accessLog{
ip: clientIP,
method: req.Method,
uri: req.RequestURI,
protocol: req.Proto,
host: req.Host,
elapsedTime: duration,
}
writeAccessLog(record)
}
答案1
得分: 2
Go是一种具有垃圾回收机制的语言。只要有对指针所指向的结构体的引用,它就会保持有效。多个连接与此无关,因为每次调用LogAccess时都会创建一个新的record,如果你跟踪相关的代码,你会发现该引用至少在writeAccessLog结束之前是存在的,具体取决于glog.Infoln的实现方式。
明确一下,&someType { ... fields ...}会创建一个新的(无名)someType实例,并返回该实例的地址。
英文:
Go is a garbage collected language. The struct the pointer is pointing to will be valid as long as there's a reference to it. Multiple connections have nothing to do with this, as this creates a new record every time LogAccess is called, and if you follow the code in question you'll see that the reference lives at least to the end of writeAccessLog, possibly longer depending on the implementation of glog.Infoln.
To be clear &someType { ... fields ...} creates a new (unnamed) instance of someType, and then returns the address of that instance.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论