写点什么

Go 中如何写注释

用户头像
baiyutang
关注
发布于: 刚刚

译者:baiyutang

原文:https://www.digitalocean.com/community/tutorials/how-to-write-comments-in-go


介绍


注释语法


// This is a comment
复制代码


块注释


// First line of a block comment// Second line of a block comment
复制代码


/*Everything herewill be considereda block comment*/
复制代码


// 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)}
复制代码

行注释

一般,行注释看起来如下:

[code]  // Inline comment about the code
复制代码


为测试而注释掉代码


// Function to add two numbersfunc addTwoNumbers(x, y int) int {    sum := x + y    return sum}
// Function to multiply two numbersfunc 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)}
复制代码

总结

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.

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.

发布于: 刚刚阅读数: 5
用户头像

baiyutang

关注

广州 2017.12.13 加入

Microservices | Golang | Cloud Nitive | “Smart work,Not hard”

评论

发布
暂无评论
Go 中如何写注释