Programs for file copying, printing, searching, sorting, counting,
and the like all have a similar structure: a loop over the input,
some computation on each element, and generation of output on the
fly or at the end.
We’ll show three variants of a program called dup
; it is partly inspired
by the Unix uniq
command, which looks for adjacent duplicate lines.
The structures and packages used are
models that can be easily adapted.
The first version of dup
prints each line that appears
more than once in the standard input, preceded by its count.
This program introduces the if
statement, the map
data type, and
the bufio
package.
// Dup1 prints the text of each line that appears more than // once in the standard input, preceded by its count. package main import ( "bufio" "fmt" "os" ) func main() { counts := make(map[string]int) input := bufio.NewScanner(os.Stdin) for input.Scan() { counts[input.Text()]++ } // NOTE: ignoring potential errors from input.Err() for line, n := range counts { if n > 1 { fmt.Printf("%d\t%s\n", n, line) } } }
As with for
, parentheses are never used
around the condition in an if
statement, but braces are required
for the body.
There can be an optional else
part that is executed if the condition is false.
A map holds a set of key/value pairs and provides
constant-time operations to store, retrieve, or test for an item in the set.
The key may be of any type whose values can be compared with ==
,
strings being the most common example; the value may be of any type
at all.
In this example, the keys are strings and the values are
int
s.
The built-in function make
creates a new empty map;
it has other uses too.
Maps are discussed at length in Section 4.3.
Each time dup
reads a line of input, the line is used as
a key into the map and the corresponding value is incremented.
The statement counts[input.Text()]++
is equivalent to these two
statements:
line := input.Text() counts[line] = counts[line] + 1
It’s not a problem if the map doesn’t yet contain that key.
The first time a new line is seen, the expression counts[line]
on the right-hand side evaluates to the zero value for its type, which
is 0
for int
.
To print the results, we use another range
-based for
loop, this time over the counts
map.
As before, each iteration produces two results, a key and the value of the map
element for that key.
The order of map iteration is not specified, but in practice it is random,
varying from one run to another.
This design is intentional, since it prevents programs from relying on
any particular ordering where none is guaranteed.
Onward to the bufio
package, which helps make input and output efficient and
convenient.
One of its most useful features is a type called
Scanner
that reads input and breaks it into lines or words; it’s
often the easiest way to process input that comes naturally in lines.
The program uses a short variable declaration to create a new variable
input
that refers to a bufio.Scanner
:
input := bufio.NewScanner(os.Stdin)
The scanner reads from the program’s standard input.
Each call to input.Scan()
reads the next line and removes the
newline character from the end; the result
can be retrieved by calling input.Text()
. The
Scan
function returns true
if there is a line and false
when there is no more input.
The function fmt.Printf
, like printf
in C and other
languages, produces formatted output from a list of expressions.
Its first argument is a format string that specifies how subsequent
arguments should be formatted.
The format of each argument is determined by a conversion
character, a letter following a percent sign.
For example, %d
formats an integer operand using decimal notation,
and %s
expands to the value of a string operand.
Printf
has over a dozen such conversions,
which Go programmers call verbs.
This table is far from a complete specification but illustrates many
of the features that are available:
%d |
decimal integer |
%x, %o, %b |
integer in hexadecimal, octal, binary |
%f, %g, %e |
floating-point number: 3.141593 3.141592653589793 3.141593e+00 |
%t |
boolean: true or false |
%c |
rune (Unicode code point) |
%s |
string |
%q |
quoted string "abc" or rune 'c' |
%v |
any value in a natural format |
%T |
type of any value |
%% |
literal percent sign (no operand) |
The format string in dup1
also contains a tab \t
and a newline \n
.
String literals may contain such escape sequences
for representing otherwise invisible characters.
Printf
does not write a newline by default.
By convention, formatting functions whose names end in f
, such
as log.Printf
and fmt.Errorf
, use
the formatting rules of fmt.Printf
, whereas those whose names end in
ln
follow Println
,
formatting their arguments as if by %v
,
followed by a newline.
Many programs read either from their standard input, as above, or from
a sequence of named files.
The next version of dup
can read from the standard input or
handle a list of file names, using os.Open
to open each one:
// Dup2 prints the count and text of lines that appear more than once // in the input. It reads from stdin or from a list of named files. package main import ( "bufio" "fmt" "os" ) func main() { counts := make(map[string]int) files := os.Args[1:] if len(files) == 0 { countLines(os.Stdin, counts) } else { for _, arg := range files { f, err := os.Open(arg) if err != nil { fmt.Fprintf(os.Stderr, "dup2: %v\n", err) continue } countLines(f, counts) f.Close() } } for line, n := range counts { if n > 1 { fmt.Printf("%d\t%s\n", n, line) } } } func countLines(f *os.File, counts map[string]int) { input := bufio.NewScanner(f) for input.Scan() { counts[input.Text()]++ } // NOTE: ignoring potential errors from input.Err() }
The function os.Open
returns two values.
The first is an open file (*os.File
)
that is used in subsequent reads by the Scanner
.
The second result of os.Open
is a value of the built-in
error
type.
If err
equals the special built-in value nil
,
the file was opened successfully.
The file is read, and when the end of the input is reached,
Close
closes the file and releases any resources.
On the other hand, if err
is not nil
, something went wrong.
In that case, the error value describes the problem.
Our simple-minded error handling prints a message on the standard error
stream using Fprintf
and the verb %v
, which displays a value of
any type in a default format,
and dup
then carries on with the next file; the continue
statement
goes to the next iteration of the enclosing for
loop.
In the interests of keeping code samples to a reasonable size, our early
examples are intentionally somewhat cavalier about error handling.
Clearly we must check for an error from os.Open
; however, we
are ignoring the less likely possibility that an error could occur while reading
the file with input.Scan
.
We will note places where we’ve skipped error checking, and we will go
into the details of error handling in Section 5.4.
Notice that the call to countLines
precedes its declaration.
Functions and other package-level entities may be declared in any order.
A map is a reference to the data structure created by
make
.
When a map is passed to a function, the function receives a copy of
the reference, so any changes the called function makes to the underlying
data structure will be visible through the caller’s map reference too.
In our example, the values inserted into the counts
map by
countLines
are seen by main
.
The versions of dup
above operate in a “streaming” mode
in which input is read and broken into lines as needed,
so in principle these programs can handle an arbitrary amount of input.
An alternative approach is to read the entire input into memory in one big gulp,
split it into lines all at once, then process the lines.
The following version, dup3
, operates in that fashion.
It introduces the function ReadFile
(from the io/ioutil
package), which reads
the entire contents of a named file, and strings.Split
,
which splits a string into a slice of substrings.
(Split
is the opposite of strings.Join
, which we
saw earlier.)
We’ve simplified dup3
somewhat.
First, it only reads named files, not the standard input, since
ReadFile
requires a file name argument.
Second, we moved the counting of the lines back into main
,
since it is now needed in only one place.
package main import ( "fmt" "io/ioutil" "os" "strings" ) func main() { counts := make(map[string]int) for _, filename := range os.Args[1:] { data, err := ioutil.ReadFile(filename) if err != nil { fmt.Fprintf(os.Stderr, "dup3: %v\n", err) continue } for _, line := range strings.Split(string(data), "\n") { counts[line]++ } } for line, n := range counts { if n > 1 { fmt.Printf("%d\t%s\n", n, line) } } }
ReadFile
returns a byte slice
that must be converted into a string
so it can be split
by strings.Split
.
We will discuss strings and byte slices at length in Section 3.5.4.
Under the covers, bufio.Scanner
, ioutil.ReadFile
, and ioutil.WriteFile
use the Read
and Write
methods of *os.File
, but it’s rare that most
programmers need to access those lower-level routines directly.
The higher-level functions like those from bufio
and io/ioutil
are easier to use.
Exercise 1.4:
Modify dup2
to print the names of all files in which
each duplicated line occurs.