【问题标题】:Updating a value from a struct in Golang从 Golang 中的结构更新值
【发布时间】:2019-07-25 13:44:50
【问题描述】:

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

【问题讨论】:

  • 使用指针代替值,即[]*Carousel。如果您使用值,则在循环内,carousel 变量是切片中内容的副本,更改副本不会更改原始内容。或者,您可以使用索引直接更新切片的内容,即(*carousels)[i].LastRun = time.Now()
  • 不错!我尝试使用 *carousels[i].LastRun = time.Now() 不带括号,但带括号它可以完美运行!

标签: go go-gorm


【解决方案1】:

要更新 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)是切片中元素的副本。因此,即使更新它,它也不会更新实际列表中的元素。

为此,您需要访问需要更新的切片的索引,然后执行更改。

【讨论】:

    猜你喜欢
    • 2022-09-29
    • 1970-01-01
    • 2016-07-30
    • 2017-10-10
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    相关资源
    最近更新 更多