go - 从 Golang 中的结构更新值

标签 go go-gorm

我正在努力更新来自 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/

相关文章:

sql - golang gorm 多对多反向引用

go - 如果发生错误并且我的 golang 应用程序没有处理它会发生什么?

postgresql - 如何使用GORM在Postgres的JSONB字段中插入数据

Golang 按位运算以及一般字节操作

concurrency - 在处理 3rd 方代码时,如何知道 Go 中会同时发生什么

go - 时间刻度数据库不创建超表

go - golang,在2个模型之间创建关系,并使用gorm使用Preload检索它们

go - db.FirstOrCreate和db.Where()。FirstOrCreate()有何区别?

go - 错误 : failed to initialize database, 拨号 tcp 时遇到错误:0:connectex:请求的地址在其上下文中无效

pointers - Golang 接口(interface)和真实类型