1.2 KiB
1.2 KiB
Problem
All these functions operate on a *parser value:
main.go:summarize(*p parser)
parser.go:func parse(p *parser, line string) (r result)func update(p *parser, r result)func err(p *parser) error
What is an object in Go?
- Object = A value of a type :
&parser{}is an object.type parser structis the definition (class/blueprint) of the object.
Methods are behaviors of objects:
- Parser needs to parse, update (analyse) the parsings, and report an error if any.
- Parser also needs to summarize the results.
- So, all these functions belong to a parser object.
Solution
- Attach the functions to the parser using methods.
- Methods are the behavior of the parser.
- Keep the methods that belong to a single type in the same file.
- Move the
summarizeintoparser.go. parser.go: Use methods.main(): Use methods of theparser.
Convince
p.shows the fields and methods belong to theparser.p.selects a method from the method set of theparser.p.methodsends thepas the first parameter to the method.pis the receiver:*pointer. It's a pointer receiver.- Receiver is copied to the method.