我正在努力更新来自 Gorm 的字段。我正在从数据库加载所有轮播,并有一个检查字段“LastRun”的自动收报机,我想在它运行时设置一个新的 time.Now() 值。
现在,我只需要更新加载的结构,所以我知道此时这不会将更改写入数据库。
在此示例中,如何更新 func Sequencer() 中的字段 carousel.LastRun?无论我做什么,它都会从数据库中获取旧值...
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"sync"
"time"
)
var (
db *gorm.DB
wg = &sync.WaitGroup{}
)
type Carousel struct {
gorm.Model
Name string
Description string
Duration uint
LastRun time.Time
Index uint8
State State
}
type State struct {
Type string
}
func main() {
path := "pkg/database/database.db"
db, err := gorm.Open("sqlite3", path)
if err != nil {
panic("failed to connect database")
}
defer db.Close()
db.AutoMigrate(&Carousel{})
var carousels []Carousel
db.Find(&carousels)
wg.Add(1)
Sequencer(&carousels)
wg.Wait()
}
func Sequencer(carousels *[]Carousel) {
ticker := time.NewTicker(1000 * time.Millisecond)
for range ticker.C {
for _, carousel := range *carousels {
next := carousel.LastRun.Add(time.Millisecond * time.Duration(carousel.Duration))
if next.Sub(time.Now()) <= 0 {
fmt.Println("Carousel: ", carousel.Name, "Last run: ", time.Since(carousel.LastRun))
carousel.LastRun = time.Now()
/* How do I update the carousel.LastRun ? */
}
}
}
}
最佳答案
要更新 carouselstruct,您可以这样做:
func Sequencer(carousels []*Carousel) {
ticker := time.NewTicker(1000 * time.Millisecond)
for range ticker.C {
for i, _ := range carousels {
carousel = carousels[i]
next := carousel.LastRun.Add(time.Millisecond * time.Duration(carousel.Duration))
if next.Sub(time.Now()) <= 0 {
fmt.Println("Carousel: ", carousel.Name, "Last run: ", time.Since(carousel.LastRun))
carousel.LastRun = time.Now()
}
}
}
}
当使用 range
时,使用的值(对于您的情况下的 carousel
var)是 slice 中元素的副本。因此,即使更新它,它也不会更新实际列表中的元素。
为此,您需要访问需要更新的 slice 的索引,然后执行更改。
关于go - 从 Golang 中的结构更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56643019/