Home > Article > Backend Development > Does go language have annotations?
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.
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.
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 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.
The Go language itself does not natively support powerful Annotations are limited to the following two types:
But first press It is not enough to be used as a function annotation, nor can it form a decorator behavior like Python.
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:
Annotations are not accepted for the following reasons:
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 语言官方没有原生的完整支持,但开源社区中也有小伙伴已经放出了大招,借助各项周边工具和库来实现特定的函数注解功能。
GitHub 项目分别如下:
使用示例如下:
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 项目所提供的思路来讲解。
分为三个步骤:
解析代码。
模板处理。
生成代码。
首先,我们需要用用 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!