golang编程教学

tech2023-05-14  107

golang编程教学

I’ve been programming in Go for a couple of years now, and while it took a little warming to in the beginning, it has become my go to language of choice for its speed, reliability and overall productivity. I’ve used it in projects both big and small, and it has yet to let me down. I’ve picked a few of the things that make Go stand out for me, and that really sum up what makes Go a pleasure to code in.

我已经在Go中编程了两年了,虽然刚开始时有点暖和,但它的速度,可靠性和整体生产率已成为我的首选语言。 我在大型和小型项目中都使用过它,但它至今还没有让我失望。 我已经选择了一些使Go脱颖而出的东西,这实际上总结了使Go成为编写代码乐趣的原因。

强大的标准库 (Robust standard library)

A lot of languages and their ecosystems have a level of “third party library” institutional knowledge. “Oh don’t use the built-in CSV parsers, use FastCSV”. “You’re using Thin? You should be using Unicorn”. “You’re using Node? IO.js is where it’s at”. This sort of fragmentation is generally due to a less-than-perfect implementation of standard library features, and creates a high barrier to entry for a language. The Go language is renowned for having a rock-solid Standard Library. More often than not, the standard library contains all you need to write your applications. For example, it has a built in ‘http’ stack that can serve your web applications without breaking a sweat – Google’s download service (dl.google.com) uses this library to serve up Chrome, Earth, Android SDK, and other large Google downloads.

许多语言及其生态系统都具有一定程度的“第三方库”机构知识。 “哦,不要使用内置的CSV解析器,请使用FastCSV”。 “您使用的是Thin吗? 您应该使用独角兽”。 “您正在使用Node? IO.js就在这里”。 这种碎片通常是由于标准库功能的实现不尽人意造成的,并且为语言的输入带来了很大的障碍。 Go语言以拥有坚如磐石的标准库而闻名。 标准库通常包含编写应用程序所需的全部内容。 例如,它具有内置的“ http”堆栈,可为您的Web应用程序提供服务而不会费劲– Google的下载服务(dl.google.com)使用此库来提供Chrome,Earth,Android SDK和其他大型Google服务下载。

静态打字 (Static typing)

Coming from a dynamic scripting past (PHP and Ruby) I was initially wary of a statically typed language. After the first frustrations around updating function expectations and returns, I now fear going back to dynamic typing. The type checker is capable of picking up incorrect function names and type assignments. Because I no longer have to write tests to assert the error behaviour of my code when wrong types are supplied, nor check that a method name is even correct, my test suites are able to focus on the expected business logic, not these basic assertions.

来自动态脚本(PHP和Ruby),最初我对静态类型的语言非常警惕。 在围绕更新函数期望值和返回值的最初挫折之后,我现在担心会回到动态类型化。 类型检查器能够选择不正确的函数名称和类型分配。 因为我不再需要编写测试来断言提供错误类型时代码的错误行为,也不必检查方法名称是否正确,所以我的测试套件能够专注于预期的业务逻辑,而不是这些基本断言。

快速编译 (Fast compilation)

Not only is Go a fast language, but it’s optimised for compile time. In reality this means your Go binaries should compile in two or three seconds. This is a serious win for developer productivity. The ability to quickly switch between code and command line when writing applications is extremely important. If a compile takes significant time, it throws a developer out of their flow. Even 10 seconds is enough for your brain to switch off; you switch context and open Reddit or Hacker News, then sometime after the compilation is done you remember to go back and see the results. This constant context switching is not something humans are great at, and your overall productivity is not the best it can be. I’ve managed to avoid this in Go.

Go不仅是一种快速的语言,而且针对编译时间进行了优化。 实际上,这意味着您的Go二进制文件应在两到三秒钟内编译。 对于开发人员来说,这是一个巨大的胜利。 编写应用程序时,在代码和命令行之间快速切换的能力非常重要。 如果编译花费大量时间,则会将开发人员从其工作流程中排除。 即使10秒也足以让您的大脑关闭。 您切换上下文并打开Reddit或Hacker News,然后在编译完成后的某个时间,您记得回头查看结果。 这种持续的上下文切换并不是人类擅长的事情,并且您的整体生产力也不是最好的。 我设法在Go中避免了这种情况。

简单并发 (Simple concurrency)

Adding concurrency to your Go applications is incredibly simple through the use of ‘goroutines’ to run code asynchronously and ‘channels’ to communicate. Go has a mantra that sums up the communication model:

通过使用“ goroutines”异步运行代码和“ channels”进行通信,向Go应用程序添加并发非常简单。 Go有一个总结通信模型的口头禅:

Do not communicate by sharing memory; instead, share memory by communicating.

不要通过共享内存进行通信; 而是通过通信共享内存。

Channels provide a mechanism to both send and receive data. These channels ensure strict ordering, and provide a method for synchronizing concurrent code. By passing data across channels, rather than accessing shared variables, there’s no need for locking access to data, and tasks that can fail in complicated and unexpected ways in other languages are concisely written in small amounts of Go. You can also easily unlock the full power of the hardware your code runs on by running your goroutines across multiple cpu cores.

通道提供了一种发送和接收数据的机制。 这些通道确保严格的排序,并提供一种同步并发代码的方法。 通过跨通道传递数据,而不是访问共享变量,无需锁定对数据的访问,并且可以用少量的Go语言简洁地编写其他语言中可能以复杂且出乎意料的方式失败的任务。 您还可以通过跨多个cpu内核运行goroutines来轻松释放代码所运行的硬件的全部功能。

官方格式 (Official formatting)

Go is very opinionated about formatting, and this may not be for some developers. The ‘gofmt’ tool that comes with Go will automatically format your code to follow the formatting standard. By hooking this tool into your editor’s save command you can ensure your files are formatted correctly. No more ‘fix whitespace’ or ‘New line here please’ comments during code review – you can focus on the things that matter, the business logic of your code. It still gives me a kick to see my code auto-formatted for me, and I have been trying to introduce tools to do this for me in other languages I work with ever since. Once you gofmt, you’ll never go back.

Go在格式化方面非常自以为是,对于某些开发人员而言可能并非如此。 Go随附的“ gofmt”工具将自动格式化您的代码,以遵循格式化标准。 通过将此工具挂接到编辑器的save命令中,可以确保文件格式正确。 在代码检查过程中,不再有“固定空白”或“请在此处换行”注释–您可以专注于重要的事情,即代码的业务逻辑。 看到我为我的代码自动格式化仍然让我大吃一惊,从那时起,我一直在尝试引入工具以我使用的其他语言为我自动进行格式化。 一旦您找到文件,便再也回不去了。

面对您的错误处理 (In yo’ face error handling)

Error handling in Go is a first class citizen. You receive errors back from any function where an error condition could occur. Often these are the second value returned from a function, so this sort of code is very prevalent:

Go中的错误处理是一流的公民。 您会从可能发生错误情况的任何函数中收到错误信息。 通常,这些是从函数返回的第二个值,因此这种代码非常普遍:

data, err := db.Query(“SELECT * FROM table”) if err != nil { // Handle your error here, perhaps by returning it // from this function for the calling code to deal with }

Having your errors as such an integral part of your code’s flow makes you think of what an error means for every particular piece of code you write. I can honestly say I’ve never thought about errors so much in my life, and this is a good thing. I now know exactly what the failure conditions of my code look like, and how they are handled. Because of this, Go code is robust code. Ignoring errors is a conscious decision, and very rarely done. While some might see this as verbose, or untidy, and it certainly does add some lines to your code, the payoff far outweighs the cost.

将错误作为代码流中不可或缺的一部分使您想到错误对于您编写的每个特定代码段意味着什么。 老实说,我从来没有想过这么多错误,这是一件好事。 我现在确切地知道代码的失败情况是什么样子,以及如何处理它们。 因此,Go代码是健壮的代码。 忽略错误是一个有意识的决定,很少这样做。 尽管有些人可能认为这很冗长或不整洁,并且确实在代码中添加了一些行,但收益远大于成本。

If any of these attributes have resonated with you, I encourage you to give Go a try. Learnable have just released my book “Level Up Your Web Applications with Go” which will take you from a complete Go novice, to writing Go Web Applications in no time.

如果这些属性中的任何一个引起了您的共鸣,建议您尝试一下Go。 Learnable刚发行了我的书“ Go升级您的Web应用程序 ”,它将使您从一个完整的Go新手,Swift变为编写Web应用程序。

Buy This Book! 买这本书!

翻译自: https://www.sitepoint.com/love-programming-go/

golang编程教学

最新回复(0)