In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "what are the advantages of Go language". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the advantages of Go language.
Conciseness
Go and Java are both C family languages, so they have similar syntax. As a result, Java developers can easily read Go code, and vice versa. Go does not need to use a semicolon (';') at the end of the statement, with a few exceptions. For me, Go's line separation is clearer and easier to read.
Both Go and Java use one of my favorite features, the garbage collector (GC), to help prevent memory leaks. Unlike C++, family C programmers need to deal with memory leaks. The garbage collector is a feature of automated memory management that lightens the burden on programmers.
Go's GC does not use the "weak generation hypothesis", but it still performs very well, and the STW (Stop-the-World) time is very short. In version 1.5, STW dropped more and more stable, while in version 1.8, it dropped to less than 1 millisecond.
Go's GC has only a few options, namely the GOGC variable that sets the initial garbage collection target percentage. Java, on the other hand, has four different garbage collectors, each with a large number of options.
Although both Java and Go are considered cross-platform, Java requires a Java virtual machine (JVM) to interpret the compiled code, while Go is a binary that compiles the code into the target platform. But I think Java is less platform-dependent than Go, because Go needs to compile binaries for the new platform every time. From a testing and DevOps perspective, compiling binaries for different platforms is time-consuming, and cross-platform Go compilation doesn't work in some cases, especially when using CGo. For Java, you can use the same jar anywhere you install JVM. Go requires a smaller RAM and does not need to install and manage virtual machines.
Reflex. Java reflection is more convenient, more popular, and more commonly used, while Go reflection seems to be more complex. Java is an object-oriented programming language, so everything except the primitive type is considered an object. If you want to use reflection, you can create a class and get the required information from the class, as follows:
Class cls = obj.getClass (); Constructor constructor = cls.getConstructor (); Method [] methods = cls.getDeclaredFields ()
This allows you to access constructors, methods, and properties, and then call or assign values to them.
Go has no concept of a class, and the structure contains only declared fields. Therefore, we need to use the "reflection" package to get the information we need:
Type Foo struct {An int `tag1: "First Tag" tag2: "Second Tag" `B string} f: = Foo {A: 10, B: "Salutations"} fType: = reflect.TypeOf (f) switch t.Kind (fType) case reflect.Struct: for I: = 0; I < t.NumField (); iTunes + {f: = t.Field (I) / /...}}
I don't think this is a big problem, but since there is no constructor for structs in Go, many primitive types must be handled separately and pointers need to be taken into account. In Go, we can pass pointers or values. The structure of Go can have a function as a field. All of this complicates the reflection of Go.
Accessibility. Java has private, protected, and public modifiers that provide different access scopes for data, methods, and objects. Go has exported/unexported similar to Java's public and private, but without modifiers. Everything that begins with an uppercase letter is exported, visible to other packages, and unexported (lowercase) variables or functions are visible only in the current package.
The big difference between Go and Java
Go is not an object-oriented programming language. Go does not have an inheritance mechanism similar to Java because it does not achieve traditional polymorphism through inheritance. In fact, it has no objects, only structures. It can simulate some object-oriented features through interfaces and letting structures implement interfaces. In addition, you can embed a structure in a structure, but an internal structure cannot access the data and methods of an external structure. Go uses combinations rather than inheritance to combine behaviors and data.
Go is an imperative language and Java is a declarative language. Go doesn't have dependency injection, and we need to explicitly wrap everything together. Therefore, try to minimize the use of things like "magic" when using Go. All code should be obvious to code reviewers. Go programmers should understand how Go code uses memory, file systems, and other resources.
Java requires developers to pay more attention to the business logic of the program and know how to create, filter, modify, and store data. The underlying and database aspects of the system are done through configuration and annotations (for example, through general frameworks such as Spring Boot). We leave boring things to the framework as much as possible. This is convenient, but the control is reversed, limiting our ability to optimize the entire process.
The order in which variables are defined. In Java, you can define variables like this:
String name
In Go, you have to write:
Name string
This was also one of the things that puzzled me when I first started using Go.
The bright side of Go
Elegant concurrency. Go has a powerful concurrency model called "communication sequential processes" or CSP. Go uses the n-to-m parser, which allows m concurrency in n system threads. Starting concurrent routines is as simple as using a keyword of Go, such as:
Go doMyWork ()
This allows doMyWork () to be executed concurrently.
Communication between processes can be done through shared memory (not recommended) and channels. We can use as many cores as the number of processes defined by the environment variable GOMAXPROCS and bring very robust and smooth parallelism. By default, the number of processes is equal to the number of cores.
Go provides a special mode to run binaries and can detect execution conditions. In this way, we can test and prove whether our program is concurrently secure.
Go run-race myapp.go
The application will run in modal detection mode.
Go provides many out-of-the-box and useful basic features, such as the "sync" package for concurrency. A singleton of type "Once" can be written as follows:
Package singleton import ("sync") type singleton struct {} var instance * singleton var once sync.Once func GetInstance () * singleton {once.Do (func () {instance = & singleton {}) return instance}
The sync package also provides a structure for concurrent map implementations, mutexes, conditional variables, and WaitGroup. The atomic package supports concurrent secure transformations and mathematical operations-- basically everything you need to write concurrent code.
The pointer. With pointers, Go has more control over how memory is allocated, garbage collector load, and other performance tuning that cannot be achieved in Java. Compared to Java, Go is more like a low-level language and supports easier and faster performance tuning.
Duck type (Duck Typing). If it walks like a duck and quacks like a duck, it must be a duck. This is true in Go: there is no need to define whether a structure implements a given interface, as long as the structure has the same method signature as the given interface, it implements the interface. This is very useful, as the caller of the code base, you can define any interface required by the external library structure. In Java, the object must explicitly declare which interfaces are implemented.
Performance analyzer. Go's performance analysis tools make performance problem analysis convenient and easy. Go's parser can reveal the program's memory allocation and CPU usage, and show it in a visual graph, making performance optimization very easy. Java also has a lot of performance analyzers, such as Java VisualVM, but they are more complex than Go and depend on the operation of JVM, so the statistics they provide are relevant to the operation of the garbage collector.
CGO . Go can be integrated with C, so you can develop applications with C code snippets in Go projects. Developers can use CGo to create Go packages that call C code. Go provides various build options for C code snippets for a given exclude/include platform.
Take the function as an argument. The Go function can be passed as a variable to another function or as a field as a structure. This versatility is refreshing. Java 8 introduces lambda, but they are not real functions, they are just single function objects.
Clear code style guidelines. The Go community provides many examples and instructions:
Https://golang.org/doc/effective_go.html
The function can return multiple arguments, which is also very useful.
Package main import "fmt" func returnMany () (int, string, error) {return 1, "example", nil} func main () {I, s, err: = returnMany () fmt.Printf ("Returned% s% s% v", I, s, err)} 5. Bad aspects of Go
There is no polymorphism (unless implemented through an interface). In Go, if there are two functions in the same package that have different parameters but have the same meaning, you must give them different names. For example, this code:
Func makeWorkInt (number int) {fmt.Printf ("Work done number% d", number)} func makeWorkStr (title string) {fmt.Printf ("Work done title% s", title)}
In this way, you will get a lot of ways, they do the same things, but the names are different, and they look "ugly".
In addition, Go does not inherit polymorphism. The structure embedded in the structure only knows its own method and knows nothing about the method of the "host" structure. For developers like me, this is particularly challenging because we transitioned from other OOP languages (one of the most basic concepts is inheritance) to Go.
Over time, however, I began to realize that this approach to polymorphism is just another way of thinking, and it makes sense, because combinations are more reliable than inheritance, and the run time is variable.
Error handling. In Go, it is entirely up to you to decide what errors to return and how to return them, so as a developer, you are responsible for returning and passing errors. There is no doubt that mistakes may be hidden, which is a pain point. Always remember to check for errors and pass them on, which is a bit annoying and unsafe.
Of course, you can use linter to check for hidden errors, but this is an aid, not a real solution. In Java, handling exceptions is much more convenient. If it's RuntimeException, you don't even have to add it to the signature of the function.
Public void causeNullPointerException () {throw new NullPointerException ("demo");} / *... * / try {causeNullPointerException ();} catch (NullPointerException e) {System.out.println ("Caught inside fun ()."); throw e; / / rethrowing the exception}
There are no generics. While generics are convenient, they add complexity, and generics are expensive in terms of type system and runtime. When building Go code, you need to deal with different types or use code generation.
There are no comments. Although you can replace some compile-time annotations with code generation, run-time annotations are not replaceable. This makes sense because Go is not declarative and should not contain any "magic" in the code. I like to use annotations in Java because they make the code more elegant, simple, and concise.
Annotations are useful when generating swagger files for HTTP server endpoints. Currently, in Go, you need to write the swagger file manually or provide special comments for endpoints. Every time the API changes, this is a very painful thing. However, annotations in Java are like magic, and people usually don't have to care about how they are implemented.
Dependency management of Go. I have previously written an article on how to use vgo and dep for dependency management in Go. The evolution of Go's reliance on management is full of ups and downs. At first, there was no reliance on management tools other than "Gopgk". Later, an experimental "Vendor" was released, which was replaced by "vgo" and then by version 1.10 "go mod". Today, we can modify the go.mod file descriptor either manually or using various Go commands (such as "go get"), but this also makes the dependency unstable.
Java has declarative tools such as Maven and Gradle for dependency management, as well as for building, deploying, and handling other CD/CI tasks. However, in Go, we have to customize the dependency management needed to build using Makefile, docker-composes, and bash scripts, which only complicates the process and stability of CD/CI.
The name of the package includes a managed domain name. For example:
Import "github.com/pkg/errors"
This is really strange and inconvenient because you can't replace someone else's implementation with your own implementation without modifying the project code base import.
In Java, the import usually starts with the company name, for example:
Import by.spirascout.public.examples.simple.Helper
The difference is that in Go, go get gets resources from by.spirascout.public. In Java, package names and domain names are not necessarily associated.
I hope that all problems related to dependency management are temporary and will be properly resolved in the future.
At this point, I believe you have a deeper understanding of "what are the advantages of the Go language?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.