golang 上下文_Golang中的上下文!

本文探讨了Golang中的上下文(Context)概念,它在并发和取消操作中的关键作用,以及如何通过翻译自的文章来深入了解其用法。
摘要由CSDN通过智能技术生成

golang 上下文

重点 (Top highlight)

让我们来一些 (Let’s get some)

Applications in golang use Contexts for controlling and managing very important aspects of reliable applications, such as cancellation and data sharing in concurrent programming. This may sound trivial but in reality, it’s not that so. The entry point for the contexts in golang is the context package. It is extremely useful and probably one of the most versatile packages of the entire language. If you haven’t come across anything dealing with contexts yet, you probably will very soon (or maybe you just didn’t pay much attention to it). The usage of context is so widespread that multiple other packages rely on it and assume you will do the same. It is definitely a key component on golang’s ecosystem.

Golang中的应用程序使用上下文来控制和管理可靠应用程序的非常重要的方面,例如并发编程中的取消和数据共享。 这听起来很琐碎,但实际上并非如此。 golang中context的入口点是context包。 它非常有用,并且可能是整个语言中功能最多的软件包之一。 如果您还没有遇到任何有关上下文的内容,那么您可能很快就会(或者也许您只是对此不太在意)。 上下文的用法是如此广泛,以至于其他多个软件包都依赖于上下文,并假设您将做同样的事情。 它绝对是golang生态系统中的关键组成部分。

Here’s the official documentation for the context package https://golang.org/pkg/context/. It’s really great and filled with practical examples. In an attempt to extend those, let’s have a look into things I have came across in real applications.

这是contexthttps://golang.org/pkg/context/的官方文档。 确实很棒,并有许多实际示例。 为了扩展这些内容,让我们看一下我在实际应用程序中遇到的事情。

有价值的环境 (Context with value)

One of the most common uses for contexts is to share data, or use request scoped values. When you have multiple functions and you want to share data between them, you can do so using contexts. The easiest way to do that is to use the function context.WithValue. This function creates a new context based on a parent context and adds a value to a given key. You can think about the internal implementation as if the context contained a map inside of it, so you can add and retrieve values by key. This is very powerful as it allows you to store any type of data inside the context. Here’s an example of adding and retrieving data with a context.

上下文最常见的用途之一是共享数据或使用请求范围的值。 当您具有多个功能并且想要在它们之间共享数据时,可以使用上下文来实现。 最简单的方法是使用context.WithValue函数。 此函数基于父上下文创建一个新上下文,并向给定键添加一个值。 你可以想想内部实现,就好像上下文包含一个map在它的内部,这样你就可以添加和键检索值。 这非常强大,因为它允许您在上下文中存储任何类型的数据。 这是一个使用上下文添加和检索数据的示例。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值