search
HomeBackend DevelopmentGolangIs go an interpreted language?
Is go an interpreted language?Mar 16, 2021 am 11:08 AM
go languageinterpreted language

go is an interpreted language. Go (also known as Golang) is a statically strongly typed, compiled, concurrent programming language with garbage collection capabilities developed by Google. The advantages of go language: easy learning curve, high development and operating efficiency, powerful standard library, formatting of source code defined at the language level, etc.

Is go an interpreted language?

The operating environment of this tutorial: windows10 system, GO 1.18, thinkpad t480 computer.

Go (also known as Golang) is a statically strongly typed, compiled language developed by Robert Griesemer, Rob Pike and Ken Thompson of Google.

Go's syntax is close to C language, but the declaration of variables is different. Go supports garbage collection. Go's parallel model is based on Tony Hall's Communicating Sequential Process (CSP). Other languages ​​that adopt a similar model include Occam and Limbo, but it also has features of Pi operations, such as channel transmission. Plugin support is opened in version 1.8, which means that some functions can now be dynamically loaded from Go.

Compared with C, Go does not include functions such as enumeration, exception handling, inheritance, generics, assertions, virtual functions, etc., but it adds slice type, concurrency, pipes, garbage collection, Language-level support for features such as interfaces. The Go 2.0 version will support generics, but has a negative attitude towards the existence of assertions, and also defends that it does not provide type inheritance.

Unlike Java, Go has built-in associative arrays (also known as hash tables (Hashes) or dictionaries (Dictionaries)), just like string types.

Advantages of the Go language

Go is easy to learn

This is true: if you If you know any programming language, you can master most of Go's syntax by studying "Go Language Journey" for a few hours, and write your first real program in a few days. Read and understand Practical Go Programming, browse the Package Documentation, play with web toolkits like Gorilla or Go Kit, and you'll be a pretty good Go developer.

This is because Go’s primary goal is simplicity. When I started learning Go, it reminded me of my first discovery of Java: a simple language and a rich but not bloated standard library. Compared with the current Java-heavy environment, learning Go is a refreshing experience. Because of Go's simplicity, Go programs are very readable, although error handling adds some headaches (more on that below).

The simplicity of the Go language can be a mistake. To quote Rob Pike, simplicity is both complex and we will see that there are many traps waiting for us to step on behind simplicity. Minimalism will make us violate the DRY (Don't Repeat Yourself) principle.

Simple concurrent programming based on goroutines and channels

Goroutines are probably the best feature of Go. They are lightweight computing threads, distinct from operating system threads.

When a Go program performs an operation that appears to be blocking I/O, the Go runtime actually suspends the goroutine and resumes it when an event indicates that a result is available. Meanwhile, other goroutines have been scheduled for execution. Therefore, under the synchronous programming model, we have the scalability advantages of asynchronous programming.

Goroutines are also lightweight: their stacks grow and shrink with demand, which means having 100s or even 1000s of goroutines is no problem.

I had a goroutine vulnerability in my old application: these goroutines were waiting for a channel to close before finishing, and the channel never closed (a common deadlock problem). This process eats 90% of the CPU for no reason, and checking expvars shows 600k idle goroutines! I'm guessing the goroutine scheduler is hogging the CPU.

Of course, actor systems like Akka can easily handle millions of actors, in part because actors don't have stacks, but they're nowhere near as simple as goroutines for writing massively concurrent request/response applications (i.e. http APIs).

Channels are a way for goroutines to communicate: they provide a convenient programming model for sending and receiving data between goroutines without having to rely on fragile low-level synchronization primitives. channels have their own set of usage patterns.

However, channels must be carefully considered, as incorrectly sized channels (which are not buffered by default) can cause deadlocks. We will also see below that using channels does not prevent race conditions because of its lack of immutability.

Rich standard library

Go’s standard library is very rich, especially for everything related to network protocol or API development: http client and server, encryption, Archive formats, compression, sending emails and more. There's even an html parser and fairly powerful template engine to generate text & html, which automatically filters out XSS attacks (such as used in Hugo).

Various APIs are generally simple and easy to understand. They sometimes seem too simplistic: This is partly because the goroutine programming model means that we only need to care about "seemingly synchronous" operations. This is also because some general functions can also replace many specialized functions, as I recently found out about time calculations.

Go has superior performance

Go is compiled into a local executable file. Many Go users come from Python, Ruby, or Node.js. For them, this is an exciting experience as they see a huge increase in the number of concurrent requests the server can handle. This is actually quite normal when you are using an interpreted language that is not concurrent (Node.js) or has a global interpreter lock. Combined with the simplicity of the language, this explains why Go is exciting.

Compared to Java, however, in raw performance benchmarks, the situation is not so clear. Where Go beats Java is in memory usage and garbage collection.

Go's garbage collector is designed to prioritize latency and avoid downtime, which is especially important in servers. This may incur higher CPU costs, but in a horizontally scalable architecture this is easily solved by adding more machines. Remember, Go was designed by Google and they are never short on resources.

Compared to Java, Go's garbage collector (GC) has less to do: a slice is a contiguous array structure, not an array of pointers like Java. Similarly, Go maps also use small arrays as buckets to achieve the same purpose. This means less work for the garbage collector and better CPU cache localization.

Go also has an advantage over Java in command line utilities: as a native executable, Go programs have no startup overhead, whereas Java first requires bytecode to be loaded and compiled.

Language-level definition of source code formatting

Some of the most heated debates in my career have occurred over the definition of code format for teams. Go solves this problem by defining a canonical format for code. The gofmt tool will reformat your code and has no options.

Whether you like it or not, gofmt defines how to format code, solving this problem once and for all.

Standardized testing framework

Go provides a good testing framework in its standard library. It supports parallel testing, benchmarking, and includes many utilities to easily test network clients and servers.

Go programs are easy to operate

Compared to Python, Ruby or Node.js, having to install a single executable file is a dream for operation and maintenance engineers. As Docker is used more and more, this problem becomes less and less, but standalone executables also mean small Docker images.

Go also has some built-in observability capabilities, making it possible to publish internal status and metrics using the expvar package, and make it easy to add new content. But be careful as they are automatically exposed in the default http request handler and are not protected. Java has something similar to JMX, but it's much more complex.

Defer statement to prevent forgetting to clean up

The purpose of the defer statement is similar to Java's finally: execute some cleanup code at the end of the current function, regardless of how this function exits . The interesting thing about defer is that it has no connection with the code block and can appear at any time. This keeps the cleanup code as close as possible to the code that needs to be cleaned up:

file, err := os.Open(fileName)
if err != nil {
    return
}
defer file.Close()
// 用文件资源的时候,我们再也不需要考虑何时关闭它

Of course, Java's trial resources are less verbose, and Rust automatically declares the resource when its owner is removed, but since Go requires you to explicitly Know about resource cleanup, so it's good to have it close to resource allocation.

New types

I like types because there are some things that annoy and scare me. For example, we treat persistent object identifiers everywhere as string or long types. passing use. We usually encode the type of id in the parameter name, but this creates subtle bugs when a function has multiple identifiers as parameters and some calls don't match the parameter order.

Go has first-class support for new types, that is, the type is an existing type and is given an independent identity that is different from the original type. In contrast to packaging, new types have no runtime overhead. This allows the compiler to catch this kind of error:

type UserId string // <-- new type
type ProductId string
func AddProduct(userId UserId, productId ProductId) {}
func main() {
    userId := UserId("some-user-id")
    productId := ProductId("some-product-id")
    // 正确的顺序: 没有问题
    AddProduct(userId, productId)
    // 错误的顺序:将会编译错误 
    AddProduct(productId, userId)
    // 编译错误:
    // AddProduct 不能用 productId(type ProductId) 作为 type UserId的参数
    // Addproduct 不能用 userId(type UserId) 作为type ProfuctId 的参数 
}

Unfortunately, the lack of generics makes working with new types cumbersome, because writing reusable code for them requires converting values ​​from primitive types.

For more programming related knowledge, please visit: Programming Video! !

The above is the detailed content of Is go an interpreted language?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
go语言有没有缩进go语言有没有缩进Dec 01, 2022 pm 06:54 PM

go语言有缩进。在go语言中,缩进直接使用gofmt工具格式化即可(gofmt使用tab进行缩进);gofmt工具会以标准样式的缩进和垂直对齐方式对源代码进行格式化,甚至必要情况下注释也会重新格式化。

go语言为什么叫gogo语言为什么叫goNov 28, 2022 pm 06:19 PM

go语言叫go的原因:想表达这门语言的运行速度、开发速度、学习速度(develop)都像gopher一样快。gopher是一种生活在加拿大的小动物,go的吉祥物就是这个小动物,它的中文名叫做囊地鼠,它们最大的特点就是挖洞速度特别快,当然可能不止是挖洞啦。

一文详解Go中的并发【20 张动图演示】一文详解Go中的并发【20 张动图演示】Sep 08, 2022 am 10:48 AM

Go语言中各种并发模式看起来是怎样的?下面本篇文章就通过20 张动图为你演示 Go 并发,希望对大家有所帮助!

【整理分享】一些GO面试题(附答案解析)【整理分享】一些GO面试题(附答案解析)Oct 25, 2022 am 10:45 AM

本篇文章给大家整理分享一些GO面试题集锦快答,希望对大家有所帮助!

tidb是go语言么tidb是go语言么Dec 02, 2022 pm 06:24 PM

是,TiDB采用go语言编写。TiDB是一个分布式NewSQL数据库;它支持水平弹性扩展、ACID事务、标准SQL、MySQL语法和MySQL协议,具有数据强一致的高可用特性。TiDB架构中的PD储存了集群的元信息,如key在哪个TiKV节点;PD还负责集群的负载均衡以及数据分片等。PD通过内嵌etcd来支持数据分布和容错;PD采用go语言编写。

go语言是否需要编译go语言是否需要编译Dec 01, 2022 pm 07:06 PM

go语言需要编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言,也就说Go语言程序在运行之前需要通过编译器生成二进制机器码(二进制的可执行文件),随后二进制文件才能在目标机器上运行。

go语言能不能编译go语言能不能编译Dec 09, 2022 pm 06:20 PM

go语言能编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言。对Go语言程序进行编译的命令有两种:1、“go build”命令,可以将Go语言程序代码编译成二进制的可执行文件,但该二进制文件需要手动运行;2、“go run”命令,会在编译后直接运行Go语言程序,编译过程中会产生一个临时文件,但不会生成可执行文件。

golang map怎么删除元素golang map怎么删除元素Dec 08, 2022 pm 06:26 PM

删除map元素的两种方法:1、使用delete()函数从map中删除指定键值对,语法“delete(map, 键名)”;2、重新创建一个新的map对象,可以清空map中的所有元素,语法“var mapname map[keytype]valuetype”。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),