Golang Scanner Package

28/12/2020
Chưa phân loại

In this lesson on Scanner package in Golang, we will study various examples on how to use Scanners in multiple ways in Go programming language. We will get started now.

Starting with Go

Just to make sure we have the environment setup consistently, here is the directory structure which I made for my Hello World program:

Here is the program we created:

package main

import "fmt"

func main() {
    fmt.Printf("Hello, world.n")
}

We can run the above program with the following command:

go run hello.go

Once we run this command, here is the output you will see:

Now that looks good. Let’s move to our main agenda.

Scanner and Bufio Package in Golang

In this post, we will go through the bufio and scanner packages.

We will start with a very simple example to split Strings into multiple words. Let’s at the following example:

package main

import (
    "bufio"
    "fmt"
    "strings"
)

func main() {
    inputStr := "golang shubham linux"
    scanner := bufio.NewScanner(strings.NewReader(inputStr))
    scanner.Split(bufio.ScanWords)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
}

The output of this program will be:

golang
shubham
linux

Here, Scanner used buffered input output by reading provided input as a Stream.

Reading a file

Now, let’s try reading a file in Go, using bufio to read a file line by line. To do this, first we create a sample file in the same directory as our Go program. Here is our file:

Next, we write our program to read this file line by line:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    fileToRead, error := os.Open("./hello.txt")
    if error != nil {
        log.Fatal(error)
    }
    defer fileToRead.Close()

    scanner := bufio.NewScanner(fileToRead)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }

    if error := scanner.Err(); error != nil {
        log.Fatal(error)
    }
}

Once we run this program, here is the output we will get

Taking User Input with bufio

This is the most useful operation actually to be performed when a user is starting with the Golang language.

We can take a user input like:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString(n)
    fmt.Println(text)
}

Let’s run this program now:

Just to note, there is another way to take input if you are Ok NOT accepting a whitespace in it:

package main

import "fmt"

var input string

func main() {
    fmt.Print("Enter Your Name=")
    fmt.Scanf("%s",&input)
    fmt.Println("Hello "+input)
}

Let’s run this program now:

Conclusion

To study, Scanner and Bufio package in Go is very useful and it is never possible to get enough. Read more examples for the package and try as much as possible on your own.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Install and Use Email Client on elementary OS

One of the handiest tools that elementary OS includes is the powerful email client. In this post, we will teach you how...
29/12/2020

HTTP analysis using Wireshark

What is HTTP? First is all the full form of HTTP is HyperText Transfer Protocol. HTTP is an application layer protocol...
29/12/2020

Performing a Cross-Site Request Forgery Attack

A CSRF attack is the one that makes authenticated users perform unwanted actions in the web application they are authenticated...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Dịch Vụ Xây Dựng Hệ Thống Peering Với Internet Exchange (IXP)
04/04/2025

Dịch Vụ Triển Khai VPN Site-to-Site & Remote Access
04/04/2025

Dịch Vụ Thiết Lập Hệ Thống Tường Lửa (Firewall)
04/04/2025

Dịch Vụ Triển Khai Hệ Thống Ảo Hóa & Cloud
04/04/2025

Dịch Vụ Triển Khai Hệ Thống Ceph
04/04/2025