Is it possible to create visible documentation for package in go? - go

How to create visible Go documentation?
That is easy to create documentation for any function in go like that:
package main
// documentation example
func DocumentedFunction() bool {
return true
}
And i can see that documentation when i call that function:
Can i write package documentation, that will be visible from editor/IDE? Do i have to install additional tools to achieve similar behaviour for package documentation?

According to the official Go documentation and this link, it should be possible to create documentation for an entire package the same way you would do it for a function:
To document a function, type, constant, variable, or even a complete package, write a regular comment directly preceding its declaration, with no blank line in between.
For example: the strings package:
// Package strings implements simple functions to manipulate UTF-8 encoded strings.
//
// For information about UTF-8 strings in Go, see https://blog.golang.org/strings.
package strings
..
..
rest of the file
So you basically just add a normal comment above the package keyword.

Related

what are the uses of semantic comments in Go?

By analogy with this question about tags I note that there are several uses of comments in go beyond pure commentary.
Examples:
go:generate can be used for code generation.
godoc uses the function name to indicate comments it should interpret
build constraints
Are there any others I've missed?
Is there a definitive list somewhere?
Some third party packages like gocontracts and go-swagger use them as well. How can they avoid conflicting with each other?
As noted comments are directives in go not just comments.
There is at the time of writing no definitive list.
This as logged as an golang issue 28532.
Therefore I propose using this answer to make one.
Uses in the go core language and tools themselves:
go:generate can be used for code generation.
godoc uses the function name to indicate comments it should interpret
Examples - document the expected output of a test (thanks #Butuzov)
build constraints (starting with '// +build')
Import comments e.g. 'package math // import "path"'
Notable uses in third party packages
gocontracts - specify preconditions as comments
go-swagger - document a ReST API using swagger
golangci e.g. //nolint[:linter1,linter2,...]
How can they avoid conflicting with each other?
If you are developing a tool that really needs to treat comments as attributes and wish to avoid conflict with other similar uses prefix your comments with a namespace like "{mytool}: "
There are some conscious attempts at namespacing.
Magic comments built into go use the "go: " prefix as in "go:generate"
(except where they don't)
go-swagger uses "swagger: "
However you still need to approach this with caution and check the list here or any other source you can find.
Also consider whether comments are the best or only approach rather than using functions instead.
Compare for instance (gocontracts):
// SomeFunc ensures:
// * !strings.HasSuffix(result, "smth")
func SomeFunc(x int) (result string) {
// ...
}
with (godbc)
func SomeFunc(x int) (result string) {
godbc.Require(strings.HasSuffix(result,"smth");
}
Examples - Allow to test function for example output.
Copy/Paste from link above.
package stringutil_test
import (
"fmt"
"github.com/golang/example/stringutil"
)
func ExampleReverse() {
fmt.Println(stringutil.Reverse("hello"))
// Output: olleh
}

Idiomatic way of documenting a Golang program, consisting of one main.go file

I wrote a Go tool which reads files and produces output based on the input. It consists of one main.go file. Where do I document what the tool does, in order to make use of godoc (or just be idiomatic)?
// Should I explain it here?
package main
// Or here?
func main() {
// code!
}
// Or somewhere else?
To document a command for godoc or pkg.go.dev, write the command documentation in the package comment.
// Command foo does bar.
package main
func main() {
// code!
}
See the comment in stringer.go and the stringer documentation for an example.
By default, godoc and pkg.go.dev hide all other doc comments in a package with the name "main".

How to get annotation of go language function?

How to get annotation of go language function?
Example:
// #annotation1
// #annotation2
func Tags() string {
return ""
}
How to get the "#annotation1" and "#annotation2"?
Short answer, there is no native support for annotations in Golang. What's being used if tags, which you can get from the reflect package.
So, you do not have annotations in Go, and to my knowledge there is no library which provides them. Depending of what you want to do, usually tags are more than enough, and you can use the language's power to achieve the desired results.
It should be possible to implement them as you can get the documentation strings, just like PHP does. However, in the big majority of cases it won't be necessary.
EDIT:
In Go, you have access to the documentation of structs, fields, methods, interfaces, functions (godoc isn't magical) through the ast package. However, it requires parsing the files, there is no function such as type.getDocComments() as in PHP.
So, an implementation is theoretically possible. However, the kind of annotations you're asking for are simply not part of Golang's philosophy. There are plenty of libraries that extensively use tags, but none use annotations.
I do not know of any native support for something that pulls specific tags from comments - however, the builtin functionality of godoc does pull from the comments directly adjacent to functions. If you are trying to build documentation, this may be useful.
In addition to godoc, I know that the golang plugin for IntelliJ pulls these comments as the help/documentation for inline completions and suggestions.
Hope this helps!

Finding functions that return a specific type

Perhaps this is a silly question, but is there a way to find all functions (in the standard library or GOPATH) that return a specific type?
For example there are many functions that take io.Writer as an argument. Now I want to know how to create an io.Writer and there are many ways to do so. But how can I find all the ways easily without guessing at packages and looking through all the methods to find those that return an io.Writer (or whatever other type I'm after)?
Edit: I should extend my question to also find types that implement a specific interface. Sticking with the io.Writer example (which admittedly was a bad example for the original question) it would be good to have a way to find any types that implement the Writer interface, since those types would be valid arguments for a function that takes takes an io.Writer and thus answer the original question when the type is an interface.
Maybe not the best way but take a look at the search field at the top of the official golang.org website. If you search for "Writer":
http://golang.org/search?q=Writer
You get many results, grouped by categories like
Types
Package-level declarations
Local declarations and uses
and Textual occurrences
Also note that io.Writer is an interface, and we all know how Go handles interfaces: when implementing an interface, there is no declaration of intent, a type implicitly implements an interface if the methods defined by the interface are declared. This means that you won't be able to find many examples where an io.Writer is created and returned because a type might be named entirely different and still be an io.Writer.
Things get a little easier if you look for a non-interface type for example bytes.Buffer.
Also in the documentation of the declaring package of the type the Index section groups functions and methods of the package by type so you will find functions and methods of the same package that return the type you're looking for right under its entry/link in the Index section.
Also note that you can check the dependencies of packages at godoc.org. For example you can see what packages import the io package which may be a good starting point to look for further examples (this would be exhausting in case of package io because it is so general that at the moment 23410 packages import it).
In my days coding I'm personally rare in need to find functions returning Int16 and error(func can return few values in Go, you know)
For second part of your question there exists wonderful cmd implements written by Dominik Honnef go get honnef.co/go/implements
After discover type that satisfy your conditions you can assume constructor for type (something like func NewTheType() TheType) would be just after TheType declaration in source code and docs. It's a proven Go practice.

Go language: Using package name inside package scope (for Examples)

I am currently writing ExampleFuncs in my Go test scripts. For example:
package hello
import "testing"
func ExampleGetSymbol() {
data := GetSymbol("AAPL")
fmt.Println(len(data.Data))
// Output: 21
}
Now, this gives me two benefits:
This example is executed when I am running go test and
It appears in the godoc documentation under func GetSymbol
One thing bothers me and I am wondering if there is anything I should do about it.
For the user that's trying to learn from this example, the line
data := GetSymbol("AAPL")
should actually be
data := hello.GetSymbol("AAPL")
but since the test is in the same scope as the package, I cannot use it like this.
So I guess the distilled version of my question would be:
Is there a way to allow package.field notation inside the package scope?
Thanks in advance
Rather than putting this in package hello, put it in package hello_test. You're allowed to have both hello and hello_test packages in the same directory, and it allows (requires) you to create your examples the way you're suggesting.
Incidentally, this also causes you to write your test cases (at least for this file) only to the public API. This is often a good thing. But if you need to write to private functions, you can split your tests into separate files, some in the hello package and some in hello_test.
BTW, documentation for this is slightly buried. You can find it in the "Test packages" section of the go cmd documentation.

Resources