doubeng9407 2019-01-31 09:24
浏览 234
已采纳

在go例程运行时如何为struct赋值?

I'm using goroutines in my project and I want to to assign the values to the struct fields but I don't know that how I will assign the values get by using mongodb quires to the struct fields I'm showing my struct and the query too.

type AppLoadNew struct{
    StripeTestKey      string                   `json:"stripe_test_key" bson:"stripe_test_key,omitempty"`
    Locations          []Locations              `json:"location" bson:"location,omitempty"`
}

type Locations struct{
   Id int `json:"_id" bson:"_id"`
   Location  string `json:"location" bson:"location"`
}

func GoRoutine(){
   values := AppLoadNew{}
   go func() {
      data, err := GetStripeTestKey(bson.M{"is_default": true})
      if err == nil {
        values.StripeTestKey := data.TestStripePublishKey
      }
  }()
  go func() {
      location, err := GetFormLocation(bson.M{"is_default": true})
      if err == nil {
        values.Locations := location
      }
  }()
  fmt.Println(values) // Here it will nothing
  // empty
}

Can you please help me that I will assign all the values to the AppLoadNew struct.

  • 写回答

2条回答 默认 最新

  • dongyue1988 2019-01-31 09:36
    关注

    In Go no value is safe for concurrent read and write (from multiple goroutines). You must synchronize access.

    Reading and writing variables from multiple goroutines can be protected using sync.Mutex or sync.RWMutex, but in your case there is something else involved: you should wait for the 2 launched goroutines to complete. For that, the go-to solution is sync.WaitGroup.

    And since the 2 goroutines write 2 different fields of a struct (which act as 2 distinct variables), they don't have to be synchronized to each other (see more on this here: Can I concurrently write different slice elements). Which means using a sync.WaitGroup is sufficient.

    This is how you can make it safe and correct:

    func GoRoutine() {
        values := AppLoadNew{}
    
        wg := &sync.WaitGroup{}
    
        wg.Add(1)
        go func() {
            defer wg.Done()
            data, err := GetStripeTestKey(bson.M{"is_default": true})
            if err == nil {
                values.StripeTestKey = data.StripeTestKey
            }
        }()
    
        wg.Add(1)
        go func() {
            defer wg.Done()
            location, err := GetFormLocation(bson.M{"is_default": true})
            if err == nil {
                values.Locations = location
            }
        }()
    
        wg.Wait()
        fmt.Println(values)
    }
    

    See a (slightly modified) working example on the Go Playground.

    See related / similar questions:

    Reading values from a different thread

    golang struct concurrent read and write without Lock is also running ok?

    How to make a variable thread-safe

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀