doujuanju3076 2017-06-16 09:55 采纳率: 0%
浏览 30
已采纳

Golang初始化后得到了空片

I have 3 struct: Queue,Config,Tasker

type Queue struct {
  Name        string
  Concurrent  int
  Connections []*redis.Client
}

type Config struct {
  Queues    []Queue
  RedisAddr string
  RedisDB   int
}

type Tasker struct {
  Config Config
}

The problem happend in this method, I initialize queue.Connections in for-loop, but I got zero length of queue.Connections outside the for-loop

func (t *Tasker) StartListening() {
  for j := 0; j < len(t.Config.Queues); j++ {
    queue := t.Config.Queues[j]
    queue.Connections = make([]*redis.Client, queue.Concurrent)
    fmt.Println(len(queue.Connections)) //here print correct length, 1 for default queue, 2 for mail queue
  }
  fmt.Println(len(t.Config.Queues[0].Connections)) //but why here print 0?
}

This is my test code

func main() {
  config := Config{
    RedisAddr: "10.1.1.59:6379",
    RedisDB:   8,
    Queues: []Queue{
      Queue{Name: "default", Concurrent: 1},
      Queue{Name: "mail", Concurrent: 2},
    },
  }
  daemon := Tasker{Config: config}
  daemon.StartListening()

}

why fmt.Println(len(t.Config.Queues[0].Connections)) is 0 outside the for-loop?

  • 写回答

1条回答 默认 最新

  • doutan1970 2017-06-16 10:03
    关注

    You are creating a new Queue instead of accessing the one in the Config structure, and this new value prevents modification to the Queue in Config.Queues. Try direct assignment:

    // ...
    
    t.Config.Queues[j].Connections = make([]*redis.Client, queue.Concurrent)
    
    // ...
    

    Or if you want to use an auxillary variable, change Config.Queues type to []*Queue:

    type Config struct {
      Queues    []*Queue
      RedisAddr string
      RedisDB   int
    }
    
    // ...
    
    config := Config{
      RedisAddr: "10.1.1.59:6379",
      RedisDB:   8,
      Queues: []*Queue{
        &Queue{Name: "default", Concurrent: 1},
        &Queue{Name: "mail", Concurrent: 2},
      },
    }
    

    Now your original code should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误