英文:
Golang struct member storing time not holding value
问题
我正在尝试将时间存储在如下的结构体中:
type TimeTest struct {
GoTime time.Time
}
然后我有一个更新函数,将GoTime设置为当前时间:
func (t TimeTest) Update() {
fmt.Println(t.GoTime.String())
t.GoTime = time.Now()
fmt.Println(t.GoTime.String())
}
在调用Update函数时,GoTime始终为0,它无法保持其值。
这里是一个示例的playground链接。
英文:
I'm trying to store a time in a struct like such
type TimeTest struct {
GoTime time.Time
}
I then have an update function that sets GoTime to the current time.
func (t TimeTest) Update() {
fmt.Println(t.GoTime.String())
t.GoTime = time.Now()
fmt.Println(t.GoTime.String())
}
GoTime is always 0 at the start of the call to Update. It never holds it's value.
Here is a playground example
答案1
得分: 4
当你定义一个接收函数时,可以在值或指针上定义它。如果你在值上定义它(就像你的例子中那样),结构体的副本会传递给接收函数,所以任何更新都会丢失,因为该副本在函数完成后被销毁。如果你在指针上定义它,那么结构体本身会被传递,所以任何更新都会影响函数调用时的实际结构体副本。
你的示例代码的修订版本:
package main
import (
"fmt"
"time"
)
type TimeTest struct {
GoTime time.Time
}
func (t *TimeTest) Update() {
fmt.Println(t.GoTime.String())
t.GoTime = time.Now()
fmt.Println(t.GoTime.String())
}
func main() {
t := TimeTest{}
for i := 0; i < 3; i++ {
t.Update()
}
}
英文:
When you define a receiving function, you can define it on a value or a pointer. If you define it on a value (as in your example), a copy of the struct is passed to the receiving func, so any updates are lost because that copy is destroyed after the function finishes. If you define it on a pointer, then the struct itself is passed, so any updates affect the actual copy of the struct the function was called with.
Revised version of your playground example:
package main
import (
"fmt"
"time"
)
type TimeTest struct {
GoTime time.Time
}
func (t *TimeTest) Update() {
fmt.Println(t.GoTime.String())
t.GoTime = time.Now()
fmt.Println(t.GoTime.String())
}
func main() {
t := TimeTest{}
for i := 0; i < 3; i++ {
t.Update()
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论