Text Diff
Below is a basic Go program to perform a diff operation (finding differences between two texts). The program is divided into logical parts, with explanations and documentation. We will use Go's standard library and implement a simple line-by-line diff that shows what lines are added or removed from one text compared to the other.
Logical Parts of the Program:
Imports and Package Declaration:
We import necessary packages:
bufio
: for reading the files line by line.fmt
: for printing results to the console.os
: for interacting with the file system.strings
: for string manipulation (though it's not actively used in this version, you might use it for further enhancements).
DiffResult Struct:
A
DiffResult
struct holds the results of the diff operation:Added
: A slice of strings that contains lines added in the new file but not present in the old file.Removed
: A slice of strings that contains lines removed in the new file but present in the old file.
ReadFile Function:
Reads a file line by line and returns the content as a slice of strings.
Handles file opening, reading, and error checking.
Uses a scanner to read each line and store them in a slice.
Diff Function:
This function performs the actual diffing:
It creates two sets (maps) to store the old and new lines.
It then compares the two sets:
Lines in the old set but not in the new set are considered "removed".
Lines in the new set but not in the old set are considered "added".
The result is a
DiffResult
struct containing the added and removed lines.
PrintDiff Function:
This function prints the diff results to the console.
It prints the removed lines with a
-
and the added lines with a+
.
Main Function:
The main function orchestrates reading the files, performing the diff, and printing the results.
File paths are hardcoded for demonstration, but they can be modified to be dynamically passed or read from user input.
Running the Program:
You can create two text files,
old_version.txt
andnew_version.txt
, and place some sample content in them.Compile and run the Go program, which will read both files, perform the diff, and print the added and removed lines.
Example Usage:
For the file
old_version.txt
:line1 line2 line3And the file
new_version.txt
:line2 line3 line4The output would be:
Removed lines: - line1 Added lines: + line4
Enhancements:
You can extend this basic program by adding more sophisticated diffing algorithms, such as the Myers' diff algorithm, for more accurate results, especially for larger and more complex text files.