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

Quản lý cơ sở dữ liệu với phpMyAdmin

phpMyAdmin là công cụ hỗ trợ quản trị MySQL trên giao diện Web nhanh chóng, dễ dàng. Nó cung cấp...
30/12/2020

Markdown Tutorial — From Setup to Syntax

Markdown is an easy to read and easy to learn markup language. Unlike HTML, XML or other markup languages, where the insane...
28/12/2020

Hướng dẫn cài đặt MariaDB trên Ubuntu 20.04

MariaDB là 1 nhánh của MySQL, được xây dựng bởi một số tác giả sáng lập ra MySQL và được sự...
30/12/2020
Bài Viết

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

Hướng dẫn fake ip bằng phần mềm SStap
10/06/2025

VPS treo game là gì? Thuê VPS treo game giá rẻ, không lo giật lag
02/06/2025

 BitBrowser – Best Anti-Detect Browser!
26/05/2025

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