I’m working through an introduction to Go, adding comments to examples for my own future reference. I have run into a behavior I’d like to avoid and am seeking help do what I want to do, not what the Go powers that be think is best for me. Here’s what I’m dealing with, when I got to the explanation of “associated functions” I added a comment to emphasize the syntax for specifying a receiver:
// Methods for structs specify the struct type "receiver" here:
// |
// V
func (s CoffeeShop) greet() {
fmt.Println("Welcome to", s.Name)
But when I saved the file, the comments were reformatted (by gofmt, I suppose) and I got this:
// Methods for structs specify the struct type s "receiver" here:
//
// |
// V
func (s CoffeeShop) greet() {
fmt.Println("Welcome to", s.Name)
}
Is there a way to preserve my formatting intent? I’m using Vim with the ALE plugin (a very nice piece of work), but of course it behaves the same way in VSCode, since they both call gofmt on Save.
The reason it’s grabbing that is: when you use multiple spaces in a comment like that, it assumes it is a code block. So, you could replace your whitespace with another character as one option:
// Methods for structs specify the struct type "receiver" here:
// ---|
// ---V
func (s CoffeeShop) greet() {
fmt.Println("Welcome to", s.Name)
}
You can also see if gofmt leaves your C-style (/* */) comments alone:
/* Methods for structs specify the struct type "receiver" here:
* |
* V */
func (s CoffeeShop) greet() {
fmt.Println("Welcome to", s.Name)
}
Both work fine on the playground but I don’t know off the top of my head if gofmt will replace C-style comments locally:
That said, what do you think about documenting it on the struct itself not one of its’ methods? You could do so like this:
// CoffeeShop represents a coffee shop.
//
// Note for future reference: structs in Go can have methods defined with
// receivers. The receiver appears between the `func` keyword and the
// method name. For example:
//
// func (s CoffeeShop) Greet() {
// fmt.Println("Welcome to", s.Name)
// }
type CoffeeShop struct {
Name string
}
And this nice thing about this is: when you hover over the CoffeeShop struct, your editor will now give you properly formatted contextual help. Here’s a screenshot from VSCode for example:
Thank You! It turns out that adding a space and a single . to the // had the desired effect. (The dot is less intrusive visually than hyphens. And since these are “memory joggers”, verbosity is not a virtue. But for more permanent usages, I’ll gve your last idea som more attention.
// Methods for structs specify the struct type s "receiver" here:
// . |
// . V
func (s CoffeeShop) Greet() {
fmt.Println("Welcome to", s.Name)