user3543433
user3543433

Reputation:

Golang struct member storing time not holding value

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

Upvotes: 0

Views: 825

Answers (1)

Serdmanczyk
Serdmanczyk

Reputation: 1224

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()
    }
}

Upvotes: 4

Related Questions