Golang结构体成员存储时间但未保存值。

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

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 (
	&quot;fmt&quot;
	&quot;time&quot;
)

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 &lt; 3; i++ {
		t.Update()
	}
}

huangapple
  • 本文由 发表于 2016年4月13日 13:30:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/36589364.html
匿名

发表评论

匿名网友

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

确定