Go中语义注释的用途是什么? [英] what are the uses of semantic comments in Go?
问题描述
类似于这个问题,关于我注意到的标签不仅仅是纯粹的评论,还有很多评论用途.
By analogy with this question about tags I note that there are several uses of comments in go beyond pure commentary.
示例:
- go:generate 可用于代码生成.
- godoc 使用函数名称来表示应解释的注释
- 构建约束
- go:generate can be used for code generation.
- godoc uses the function name to indicate comments it should interpret
- build constraints
还有其他我想念的吗?
在某个地方有明确的清单吗?
Is there a definitive list somewhere?
一些第三方软件包,例如 gocontracts 和
Some third party packages like gocontracts and go-swagger use them as well. How can they avoid conflicting with each other?
推荐答案
如所述注释是指令在旅途中不仅仅是评论.
在编写最终列表时没有.记录为 golang问题28532 .
There is at the time of writing no definitive list. This as logged as an golang issue 28532.
因此,我建议使用此答案来做一个.
Therefore I propose using this answer to make one.
使用go核心语言和工具本身:
Uses in the go core language and tools themselves:
- go:generate 可用于代码生成.
- godoc 使用函数名称来表示应解释的注释
- 示例-记录测试的预期输出(感谢@Butuzov)
- 构建约束(以'//+ build ')
- 导入评论,例如'包数学//导入路径" '
- go:generate can be used for code generation.
- godoc uses the function name to indicate comments it should interpret
- Examples - document the expected output of a test (thanks @Butuzov)
- build constraints (starting with '// +build')
- Import comments e.g. 'package math // import "path"'
在第三方程序包中的显着用途
Notable uses in third party packages
- gocontracts -将前提条件指定为注释
- go-swagger -使用swagger记录ReST API
- golangci 例如//nolint [:linter1,linter2,...]
- gocontracts - specify preconditions as comments
- go-swagger - document a ReST API using swagger
- golangci e.g. //nolint[:linter1,linter2,...]
他们如何避免彼此冲突?
How can they avoid conflicting with each other?
如果您要开发的工具确实需要将注释视为属性,并希望避免与其他类似用途发生冲突,请在注释之前添加一个名称空间,例如" {mytool} :"
If you are developing a tool that really needs to treat comments as attributes and wish to avoid conflict with other similar uses prefix your comments with a namespace like "{mytool}: "
有一些有意识的命名空间尝试.内置到go中的魔术注释使用"go:"前缀,如"go:generate"中一样(除非他们没有)
There are some conscious attempts at namespacing. Magic comments built into go use the "go: " prefix as in "go:generate" (except where they don't)
go-swagger使用"swagger:"
go-swagger uses "swagger: "
但是,您仍然需要谨慎处理并检查此处的列表或您可以找到的任何其他来源.
However you still need to approach this with caution and check the list here or any other source you can find.
还要考虑注释是否是最好的或仅方法,而不是使用函数.例如进行比较( gocontracts ):
Also consider whether comments are the best or only approach rather than using functions instead. Compare for instance (gocontracts):
// SomeFunc ensures:
// * !strings.HasSuffix(result, "smth")
func SomeFunc(x int) (result string) {
// ...
}
带有( godbc )
func SomeFunc(x int) (result string) {
godbc.Require(strings.HasSuffix(result,"smth");
}
这篇关于Go中语义注释的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!