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

How to Install PostgreSQL on Debian

Debian is one of the most successful and independent linux operation system distributions and PostgreSQL is the same for...
29/12/2020

Oracle Linux vs RedHat

Oracle and Red Hat are big names in the world of enterprise Linux. With more similarities than differences, the choice between...
12/02/2020

Manjaro Deepin 16.08 released with Deepin Desktop v15.3

The release of Manjaro Deepin 16.08 to the Manjaro Community was made available on manjaro website. Manjaro is a user-friendly...
28/12/2020
Bài Viết

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

Tìm Hiểu Về Thuê Proxy US – Lợi Ích và Cách Sử Dụng Hiệu Quả
11/12/2024

Mua Proxy V6 Nuôi Facebook Spam Hiệu Quả Tại Onetcomvn
03/06/2024

Hướng dẫn cách sử dụng ProxyDroid để duyệt web ẩn danh
03/06/2024

Mua proxy Onet uy tín tại Onet.com.vn
03/06/2024

Thuê mua IPv4 giá rẻ, tốc độ nhanh, uy tín #1
28/05/2024