Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the convention for code lines with comments?

The Go model of code formatting conventions is "gofmt is the convention". There is one part of that convention I'm having difficulty in understanding, and it would be great to have a formal definition of which gofmt is an implementation, rather than having to deduce the model from empirical examples. Here's a sample.

Before go fmt:

func sieve(mine int,                  // This instance's own prime
           inch chan int,             // Input channel from lower primes
           done chan int,             // Channel for signalling shutdown
           count int) {               // Number of primes - counter
    start := true                     // First-number switch
    ouch := make(chan int)            // Output channel, this instance
    fmt.Printf("%v ", mine)           // Print this instance's prime

After go fmt:

func sieve(mine int, // This instance's own prime
    inch chan int, // Input channel from lower primes
    done chan int, // Channel for signalling shutdown
    count int) { // Number of primes - counter
    start := true                                 // First-number switch
    ouch := make(chan int)                        // Output channel, this instance
    fmt.Printf("%v ", mine)                       // Print this instance's prime

Can anyone help me understand what's going on here? That is, why have some comments been detrimentally compressed, and others expanded? Some theories:

  • This is so ugly it must mean that code without comments on the same line is preferred
  • There's a bug in gofmt
  • Incomplete (in some way) lines are treated differently from complete one
  • Something else?
like image 204
Brent.Longborough Avatar asked Feb 04 '16 12:02

Brent.Longborough


1 Answers

Conventionally, arguments are described in the function/method documentation. Consider math/big.(*Int).Exp docs:

// Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z.
// If y <= 0, the result is 1 mod |m|; if m == nil or m == 0, z = x**y.
// See Knuth, volume 2, section 4.6.3.
func (z *Int) Exp(x, y, m *Int) *Int {

The main comment explains what x, y and m are and the relationships between them. This is how it looks rendered by godoc.

Same for code, each line usually has its own comment line:

// First-number switch.
start := true
// Output channel, this instance.
ouch := make(chan int)
// Print this instance's prime.
fmt.Printf("%v ", mine)
like image 197
Ainar-G Avatar answered Oct 22 '22 20:10

Ainar-G