The go language has no annotations. The reasons why the go language does not support annotations: 1. Go prefers a clear and explicit programming style in design; 2. Compared with existing code methods, this new method of decorator does not provide more than the existing methods. The advantage is big enough to overturn the original design idea; 3. There is very little support from the votes in the community.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
The special thing is that Go has some features that other languages do not have. The most classic one is that N Java students are looking for where the annotations of the Go language are and they always have to explain.
To this end, today Jianyu will take you to understand the use and situation of Go language annotations.
What is annotation
Understand the history
Where did Annotation first appear? could not find it. But it is clear that in the use of annotations, Java annotations are the most classic. In order to facilitate understanding, we do a preliminary understanding of annotations based on Java.
In 2002, JSR-175 proposed "A Metadata Facility for the Java Programming Language", which is to provide metadata tools for the Java programming language.
This is the source of the most widely used annotation (Annotation). Examples are as follows:
// @annotation1// @annotation2func Hello() string { return ""}
is formatted with “@” as the annotation identifier.
Annotation example
Extracted from an annotation example from @wikipedia:
//等同于 @Edible(value = true) @Edible(true) Item item = new Carrot(); public @interface Edible { boolean value() default false; } @Author(first = "Oompah", last = "Loompah") Book book = new Book(); public @interface Author { String first(); String last(); } // 该标注可以在运行时通过反射访问。 @Retention(RetentionPolicy.RUNTIME) // 该标注只用于类内方法。 @Target({ElementType.METHOD}) public @interface Tweezable { }
In the above example, a series of definitions are made through annotations , declaration, assignment, etc. If you are not familiar with the existing annotations of the language, or if you make more complex annotations, there will be a certain cost of understanding.
It is often said in the industry that annotations are "encoding on the source code". The existence of annotations has clear advantages and disadvantages. What do you think?
The role of annotations
The functions of annotations are divided into the following points:
provided to the compiler Info: Annotations can be used by the compiler to detect errors or support warnings.
Compile-time and deployment-time processing: Software tools can process annotation information to generate code, XML files, etc.
Runtime processing: Some annotations can be checked at runtime and used for other purposes.
Where are the Go annotations
Current situation
The Go language itself does not natively support powerful Annotations are limited to the following two types:
- Compile-time generation: go:generate
- Compile-time constraints: go:build
But first press It is not enough to be used as a function annotation, nor can it form a decorator behavior like Python.
Why not support
Someone has made a similar proposal on Go issues,
Go Contributor @ianlancetaylor gave a clear answer,Go is designed to favor a clear, explicit programming style.
The advantages and disadvantages of thinking are as follows:
- Advantages: I don’t know what benefits Go can get from adding decorators, and I haven’t been able to clearly demonstrate it in issues.
- Disadvantages: It is clear that there will be accidental settings.
Annotations are not accepted for the following reasons:
- Compared with existing code methods, this new method of decorator does not provide more advantages than the existing methods. , big enough to overturn the original design idea.
- There is very little support for voting within the community (voting based on emoticons), and there is not much feedback from users.
Some friends may say that if there are annotations as decorators, the code will be much simpler.
The attitude of the Go team is very clear
Go believes that readability is more important. If you just write a little more code, it is still acceptable after weighing the balance. .
用 Go 实现注解
虽然 Go 语言官方没有原生的完整支持,但开源社区中也有小伙伴已经放出了大招,借助各项周边工具和库来实现特定的函数注解功能。
GitHub 项目分别如下:
- MarcGrol/golangAnnotations
- u2takey/go-annotation
使用示例如下:
package tourdefrance//go:generate golangAnnotations -input-dir .// @RestService( path = "/api/tour" )type TourService struct{}type EtappeResult struct{ ... }// @RestOperation( method = "PUT", path = "/{year}/etappe/{etappeUid}" )func (ts *TourService) addEtappeResults(c context.Context, year int, etappeUid string, results EtappeResult) error { return nil}
对 Go 注解的使用感兴趣的小伙伴可以自行查阅使用手册。
我们更多的关心,Go 原生都没支持,那么开源库都是如何实现的呢?在此我们借助 MarcGrol/golangAnnotations 项目所提供的思路来讲解。
分为三个步骤:
解析代码。
模板处理。
生成代码。
解析 AST
首先,我们需要用用 go/ast 标准库获取代码所生成的 AST Tree 中需要的内容和结构。
示例代码如下:
parsedSources := ParsedSources{ PackageName: "tourdefrance", Structs: []model.Struct{ { DocLines: []string{"// @RestService( path = "/api/tour" )"}, Name: "TourService", Operations: []model.Operation{ { DocLines: []string{"// @RestOperation( method = "PUT", path = "/{year}/etappe/{etappeUid}"}, ... }, }, }, },}
我们可以看到,在 AST Tree 中能够获取到在示例代码中所定义的注解内容,我们就可以依据此去做很多奇奇怪怪的事情了。
模板生成
紧接着,在知道了注解的输入是什么后,我们只需要根据实际情况,编写对应的模板生成器 code-generator 就可以了。
我们会基于 text/template 标准库来实现,比较经典的像是 kubernetes/code-generator 是一个可以参考的实现。
代码实现完毕后,将其编译成 go plugin,便于我们在下一步调用就可以了。
代码生成
最后,万事俱备只欠东风。差的就是告诉工具,哪些 Go 文件中包含注解,需要我们去生成的。
这时候我们可以使用 //go:generate
在 Go 文件声明。就像前面的项目中所说的:
//go:generate golangAnnotations -input-dir .
声明该 Go 文件需要生成,并调用前面编写好的 golangAnnotations 二进制文件,就可以实现基本的 Go 注解生成了。
总结
今天在这篇文章中,我们介绍了注解(Annotation)的历史背景。同时我们针对 Go 语言目前原生的注解支持情况进行了说明。
也面向为什么 Go 没有像 Java 那样支持强大的注解进行了基于 Go 官方团队的原因解释。如果希望在 Go 实现注解的,也提供了相应的开源技术方案。
The above is the detailed content of Does go language have annotations?. For more information, please follow other related articles on the PHP Chinese website!

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)