如何在Go例程中对结构体进行赋值操作?
时间:2024-03-09
浏览:217
作者:佚名
有志者,事竟成!如果你在学习Golang,那么本文《如何在Go例程中对结构体进行赋值操作?》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
我在我的项目中使用 goroutine,我想将值分配给结构字段,但我不知道如何将使用 mongodb quires 获得的值分配给我正在显示的结构字段结构和查询也是如此。
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
}
您能否帮我将所有值分配给 apploadnew 结构。
解决方案
在 go 中,没有任何值对于并发读写(来自多个 goroutine)是安全的。您必须同步访问。
可以使用 sync.Mutex 或 sync.RWMutex 保护从多个 goroutine 读取和写入变量,但在您的情况下还涉及其他问题:您应该等待 2 个启动的 goroutine 完成。为此,首选解决方案是 sync.WaitGroup。
由于 2 个 goroutine 写入结构体的 2 个不同字段(充当 2 个不同的变量),因此它们不必彼此同步(请参阅此处的更多信息:Can I concurrently write different slice elements)。这意味着使用 sync.waitgroup 就足够了。
这是确保安全和正确的方法:
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)
}
查看 Go Playground 上的(稍作修改的)工作示例。
查看相关/类似问题:
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
您可以将 sync 包与 waitgroup 一起使用,这是一个示例:
package main
import (
"fmt"
"sync"
"time"
)
type foo struct {
one string
two string
}
func main() {
f := foo{}
var wg sync.waitgroup
wg.add(1)
go func() {
defer wg.done()
// perform long calculations
<-time.after(time.second * 1)
f.one = "foo"
}()
wg.add(1)
go func() {
defer wg.done()
// perform long calculations
<-time.after(time.second * 2)
f.two = "bar"
}()
fmt.printf("before %+v\n", f)
wg.wait()
fmt.printf("after %+v\n", f)
}
输出:
Before {One: Two:}
After {One:foo Two:bar}以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
