【发布时间】:2023-03-18 19:14:01
【问题描述】:
我有一个Jobs 结构体,其中包含Job 类型的结构体片段。我想遍历每个 Job 并“执行”它们,更新它们在此过程中的状态。
代码如下:
package main
import (
"fmt"
"strconv"
)
type Job struct {
id int
status string
}
type Jobs struct {
jobs []Job
}
func main() {
jobs := Jobs{}
job := Job{id: 1, status: "pending"}
jobs.load(job)
job2 := Job{id: 2, status: "pending"}
jobs.load(job2)
fmt.Println(jobs) // jobs should be pending
jobs.execute()
fmt.Println(jobs) // jobs should be executing
}
func (j *Jobs) load(job Job) {
j.jobs = append(j.jobs, job)
}
func (j *Jobs) execute() {
for _, job := range j.jobs {
if err := job.execute(); err != nil {
id := strconv.Itoa(job.id)
fmt.Println("error occurred when executing job #" + id)
}
}
}
func (j *Job) execute() error {
j.status = "executing"
fmt.Println("Executing job")
// return errors.New("error when executing job")
return nil
}
运行时的输出:
{[{1 pending} {2 pending}]}
Executing job
Executing job
{[{1 pending} {2 pending}]}
预期输出:
{[{1 pending} {2 pending}]}
Executing job
Executing job
{[{1 executing} {2 executing}]}
我想我在某处丢失了一个指针,但我无法得到它。
【问题讨论】: