golang go语言
介绍 (Introduction)
Comments are lines that exist in computer programs that are ignored by compilers and interpreters. Including comments in programs makes code more readable for humans as it provides some information or explanation about what each part of a program is doing.
注释是计算机程序中存在的行,但编译器和解释器会忽略它们。 在程序中包含注释可使代码对人类更易读,因为它提供了有关程序每个部分正在做什么的信息或解释。
Depending on the purpose of your program, comments can serve as notes to yourself or reminders, or they can be written with the intention of other programmers being able to understand what your code is doing.
根据您的程序的目的,注释可以用作您自己的注释或提醒,也可以在其他程序员能够理解您的代码在做什么的情况下编写注释。
In general, it is a good idea to write comments while you are writing or updating a program as it is easy to forget your thought process later on, and comments written later may be less useful in the long term.
通常,在编写或更新程序时写注释是个好主意,因为以后很容易忘记您的思考过程,而从长远来看,以后写的注释可能没有太大用处。
注释语法 (Comment Syntax)
Comments in Go begin with a set of forward slashes (//
) and continue to the end of the line. It is idiomatic to have a white space after the set of forward slashes.
Go中的注释以一组正斜杠( //
)开头,并继续到该行的末尾。 在一组正斜杠之后留一个空格是很常见的。
Generally, comments will look something like this:
通常,评论将如下所示:
// This is a comment
Comments do not execute, so there will be no indication of a comment when running a program. Comments are in the source code for humans to read, not for computers to execute.
注释不执行,因此在运行程序时不会有注释的迹象。 注释在源代码中供人类阅读,而不是供计算机执行。
In a “Hello, World!” program, a comment may look like this:
在“你好,世界!”中 程序,注释可能如下所示:
package main
import (
"fmt"
)
func main() {
// Print “Hello, World!” to console
fmt.Println("Hello, World!")
}
In a for
loop that iterates over a slice, comments may look like this:
在迭代切片的for
循环中,注释可能如下所示:
package main
import (
"fmt"
)
func main() {
// Define sharks variable as a slice of strings
sharks := []string{"hammerhead", "great white", "dogfish", "frilled", "bullhead", "requiem"}
// For loop that iterates over sharks list and prints each string item
for _, shark := range sharks {
fmt.Println(shark)
}
}
Comments should be made at the same indent as the code it is commenting. That is, a function definition with no indent would have a comment with no indent, and each indent level following would have comments that are aligned with the code it is commenting.
注释应与注释的代码缩进相同。 也就是说,没有缩进的函数定义将具有没有缩进的注释,并且紧随其后的每个缩进级别将具有与其所注释的代码对齐的注释。
For example, here is how the main
function is commented, with comments following each indent level of the code:
例如,这是注释main
功能的方式,在代码的每个缩进级别之后都有注释:
package main
import "fmt"
const favColor string = "blue"
func main() {
var guess string
// Create an input loop
for {
// Ask the user to guess my favorite color
fmt.Println("Guess my favorite color:")
// Try to read a line of input from the user. Print out the error 0
if _, err := fmt.Scanln(&guess); err != nil {
fmt.Printf("%s\n", err)
return
}
// Did they guess the correct color?
if favColor == guess {
// They guessed it!
fmt.Printf("%q is my favorite color!\n", favColor)
return
}
// Wrong! Have them guess again.
fmt.Printf("Sorry, %q is not my favorite color. Guess again.\n", guess)
}
}
Comments are made to help programmers, whether it is the original programmer or someone else using or collaborating on the project. If comments cannot be properly maintained and updated along with the code base, it is better to not include a comment rather than write a comment that contradicts or will contradict the code.
进行注释以帮助程序员,无论是原始程序员还是在项目中使用或协作的其他人。 如果注释不能随代码库正确维护和更新,则最好不要包含注释,而不要写与代码矛盾或矛盾的注释。
When commenting code, you should be looking to answer the why behind the code as opposed to the what or how. Unless the code is particularly tricky, looking at the code can generally answer the what or how, which is why comments are usually focused around the why.
当代码注释,你应该寻找回答为什么而不是在什么或怎么后面的代码。 除非代码特别棘手,否则查看代码通常可以回答“ 什么”或“ 如何” ,这就是为什么注释通常围绕“ 为什么”的原因 。
阻止评论 (Block Comments)
Block comments can be used to explain more complicated code or code that you don’t expect the reader to be familiar with.
块注释可用于解释更复杂的代码或您不希望读者熟悉的代码。
You can create block comments two ways in Go. The first is by using a set of double forward slashes and repeating them for every line.
您可以在Go中以两种方式创建块注释。 第一种是使用一组双正斜杠并针对每行重复它们。
// First line of a block comment
// Second line of a block comment
The second is to use opening tags (/*
) and closing tags (*/
). For documenting code, it is considered idiomatic to always use //
syntax. You would only use the /* ... */
syntax for debugging, which we will cover later in this article.
第二种是使用开始标记( /*
)和结束标记( */
)。 对于文档代码,始终使用//
语法被认为是惯用的。 您将只使用/* ... */
语法进行调试,我们将在本文后面介绍。
/*
Everything here
will be considered
a block comment
*/
In this example, the block comment defines what is happening in the MustGet()
function:
在此示例中,块注释定义了MustGet()
函数中发生的情况:
// MustGet will retrieve a url and return the body of the page.
// If Get encounters any errors, it will panic.
func MustGet(url string) string {
resp, err := http.Get(url)
if err != nil {
panic(err)
}
// don't forget to close the body
defer resp.Body.Close()
var body []byte
if body, err = ioutil.ReadAll(resp.Body); err != nil {
panic(err)
}
return string(body)
}
It is common to see block comments at the beginning of exported functions in Go; these comments are also what generate your code documentation. Block comments are also used when operations are less straightforward and are therefore demanding of a thorough explanation. With the exception of documenting functions, you should try to avoid over-commenting the code and trust other programmers to understand Go, unless you are writing for a particular audience.
在Go中导出函数的开头通常会看到块注释。 这些注释也是生成您的代码文档的原因。 当操作不太直接,因此需要全面解释时,也会使用块注释。 除文档功能外,除非您是为特定读者编写的,否则您应尽量避免过多注释代码并信任其他程序员以了解Go。
内联评论 (Inline Comments)
Inline comments occur on the same line of a statement, following the code itself. Like other comments, they begin with a set of forward slashes. Again, it’s not required to have a whitespace after the forward slashes, but it is considered idiomatic to do so.
内联注释出现在语句的同一行,紧随代码本身。 像其他注释一样,它们以一组正斜杠开头。 同样,不需要在正斜杠后使用空格,但是这样做是惯用的。
Generally, inline comments look like this:
通常,内联注释如下所示:
[code] // Inline comment about the code
Inline comments should be used sparingly, but can be effective for explaining tricky or non-obvious parts of code. They can also be useful if you think you may not remember a line of the code you are writing in the future, or if you are collaborating with someone who you know may not be familiar with all aspects of the code.
内联注释应谨慎使用,但可以有效地解释棘手或不明显的代码部分。 如果您认为自己可能不记得将来编写的代码行,或者与认识的人可能并不熟悉代码的所有方面的人员合作,那么它们也很有用。
For example, if you don’t use a lot of math in your Go programs, you or your collaborators may not know that the following creates a complex number, so you may want to include an inline comment about that:
例如,如果您在Go程序中不使用大量数学,则您或您的合作者可能不知道以下代码会创建一个复数,因此您可能希望对此添加内联注释:
z := x % 2 // Get the modulus of x
You can also use inline comments to explain the reason behind doing something, or to provide some extra information, as in:
您还可以使用内联注释来说明执行某项操作的原因,或提供一些额外的信息,例如:
x := 8 // Initialize x with an arbitrary number
You should only use inline comments when necessary and when they can provide helpful guidance for the person reading the program.
您仅应在必要时使用内嵌注释,并且它们可以为阅读程序的人员提供有用的指导。
注释掉测试代码 (Commenting Out Code for Testing)
In addition to using comments as a way to document code, you can also use opening tags (/*
) and closing tags (*/
) to create a block comment. This allows you to comment out code that you don’t want to execute while you are testing or debugging a program you are currently creating. That is, when you experience errors after implementing new lines of code, you may want to comment a few of them out to see if you can troubleshoot the precise issue.
除了使用注释作为记录代码的方式之外,还可以使用开始标签( /*
)和结束标签( */
)创建块注释。 这样,您就可以在测试或调试当前正在创建的程序时,注释掉不想执行的代码。 也就是说,当您在实施新代码行后遇到错误时,您可能希望将其中的一些注释掉,以查看是否可以对确切的问题进行故障排除。
Using the /*
and */
tags can also allow you to try alternatives while you’re determining how to set up your code. You can also use block comments to comment out code that is failing while you continue to work on other parts of your code.
使用/*
和*/
标记还可以让您在确定如何设置代码时尝试其他方法。 您还可以使用块注释来注释掉在继续处理代码其他部分时失败的代码。
// Function to add two numbers
func addTwoNumbers(x, y int) int {
sum := x + y
return sum
}
// Function to multiply two numbers
func multiplyTwoNumbers(x, y int) int {
product := x * y
return product
}
func main() {
/*
In this example, we're commenting out the addTwoNumbers
function because it is failing, therefore preventing it from executing.
Only the multiplyTwoNumbers function will run
a := addTwoNumbers(3, 5)
fmt.Println(a)
*/
m := multiplyTwoNumbers(5, 9)
fmt.Println(m)
}
Note: Commenting out code should only be done for testing purposes. Do not leave snippets of commented out code in your final program.
注意 :注释掉代码仅应出于测试目的。 不要在最终程序中留下注释掉的代码片段。
Commenting out code with the /*
and */
tags can allow you to try out different programming methods as well as help you find the source of an error through systematically commenting out and running parts of a program.
使用/*
和*/
标记注释代码可以使您尝试不同的编程方法,并且可以通过系统地注释和运行程序的各个部分来帮助您找到错误的来源。
结论 (Conclusion)
Using comments within your Go programs helps to make your programs more readable for humans, including your future self. Adding appropriate comments that are relevant and useful can make it easier for others to collaborate with you on programming projects and make the value of your code more obvious.
在Go程序中使用注释有助于使程序对人类(包括您将来的自我)更具可读性。 添加相关且有用的适当注释可以使其他人更轻松地与您合作进行编程项目,并使代码的价值更加明显。
Commenting your code properly in Go will also allow for you to use the Godoc tool. Godoc is a tool that will extract comments from your code and generate documentation for your Go program.
在Go中正确注释您的代码还将使您能够使用Godoc工具。 Godoc是一种将从代码中提取注释并为Go程序生成文档的工具。
翻译自: https://www.digitalocean.com/community/tutorials/how-to-write-comments-in-go
golang go语言