Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean if a field is "filtered" in Go?

Tags:

go

godoc

In the Go documentation a type often shows only the exported fields. For example, the time.Timer documentation (https://golang.org/pkg/time/#Timer) shows the following:

type Timer

The Timer type represents a single event. When the Timer expires, the current time will be sent on C, unless the Timer was created by AfterFunc. A Timer must be created with NewTimer or AfterFunc.

type Timer struct {
     C <-chan Time
     // contains filtered or unexported fields
}

Go capitilizes to differentiate exported vs unexported fields, so this is clear. However, what does it mean (for example in the context of the comment above) to contain "filtered" fields?

like image 950
Andy Fusniak Avatar asked Mar 18 '20 12:03

Andy Fusniak


1 Answers

That comment is produced by the go/printer code based on the AST passed to it. Some of the AST nodes have a field that flags them as incomplete and this field is used by the printer to decide whether or not to print that comment. However the printer has no way of knowing the rules and reasons for why that field was set to true or false and so by convention it is assumend it was done by a filter, the most common one being exportFilter, hence the language.

The Incomplete field is exported and can be set to true/false by anything that has access to the AST. You could walk the AST yourself setting each Incomplete field to true while leaving the nodes intact and then passing the AST to the printer which would then produce structs with all their fields, exported and unexported, and also that comment.

Godoc filters the AST with ast.FileExports which by default removes only unexported nodes, and then passes the AST to the printer. So in the case of Godoc the "filtered" in that comment is synonymous with "unexported".


Playground link to illustrate the printer's behavior.

like image 79
mkopriva Avatar answered Nov 08 '22 12:11

mkopriva