Book Image

Hands-On Go Programming

By : Tarik Guney
Book Image

Hands-On Go Programming

By: Tarik Guney

Overview of this book

<p>With its C-like speed, simplicity, and power for a growing number of system-level programming domains, Go has become increasingly popular among programmers. Hands-On Go Programming teaches you the Go programming by solving commonly faced problems with the help of recipes. You will start by installing Go binaries and get familiar with the tools used for developing an application. Once you have understood these tasks, you will be able to manipulate strings and use them in built-in function constructs to create a complex value from two floating-point values. You will discover how to perform an arithmetic operation date and time, along with parsing them from string values. In addition to this, you will cover concurrency in Go, performing various web programming tasks, implementing system programming, reading and writing files, and honing many fundamental Go programming skills such as proper error handling and logging, among others. Whether you are an expert programmer or newbie, this book helps you understand how various answers are programmed in the Go language.</p>
Table of Contents (18 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributor
Preface
Index

Counting lines in a file


In this section, we're going to see how to count the lines of a file. Consider that we have a file and it has a bunch of names in each line, and we have to count how many lines there are in the file. First, we will open our file using the os.Open package and the name of our file will be names.txt. It returns an error, but for this example, we're not going to care about the error because we know that the file exists. So, I'm going to use a file scanner to scan the file. We have the bufio.NewScanner package that has the new scanner and it accepts a reader so we can pass the file. The line count will start from 0 and we are going to do this for fileScanner.scan. Thus, as long as it scans, it will increment the line count. Finally, we're going to write the number of the line to the console. Of course, when everything is done, we will use the defer file.Close() function. Let's check the code:

package main
import (
  "os"
  "bufio"
  "fmt"
)
func main() {
  file, _ := os...