注释
发布者:admin 发表于:417天前 阅读数:738 评论:0

在我们继续讨论更大的项目之前,我想花几分钟时间谈论一下注释。

Good code has lots of comments, bad code requires lots of comments.(好的代码有很多注释,坏代码需要很多注释。) — Dave Thomas and Andrew Hunt (The Pragmatic Programmer)

注释对 Go 语言程序的可读性非常重要。 注释应该做的三件事中的一件:

注释应该解释其作用。

注释应该解释其如何做的。

注释应该解释其原因。

第一种形式是公共符号注释的理想选择:

// Open opens the named file for reading.
// If successful, methods on the returned file can be used for reading.

第二种形式非常适合在方法中注释:

// queue all dependant actions
var results []chan error
for _, dep := range a.Deps {
        results = append(results, execute(seen, dep))
}

第三种形式是独一无二的,因为它不会取代前两种形式,但与此同时它并不能代替前两种形式。 此形式的注解用以解释代码的外部因素。 这些因素脱离上下文后通常很难理解,此注释的为了提供这种上下文。

return &v2.Cluster_CommonLbConfig{
    // Disable HealthyPanicThreshold
        HealthyPanicThreshold: &envoy_type.Percent{
            Value: 0,
        },
}

在此示例中,无法清楚地明白 HealthyPanicThreshold 设置为零百分比的效果。 需要注释 0 值将禁用 panic 阀值。