Is go an interpreted language?

青灯夜游
Release: 2023-02-13 15:32:01
Original
5309 people have browsed it

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() // 用文件资源的时候,我们再也不需要考虑何时关闭它
Copy after login

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 的参数 }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!