Friday, February 15, 2019

User input in Go language

Taking a user input in Go language is easy. Let's go through a few examples on how to do this.

We shall use the function provided by the fmt package to take user input.

Reading an Integer from console

Look at the example program below. Here we ask the user to input an integer and we use the Scan function of the fmt package to store the input into a integer variable. Then we go on to print it's value to confirm that our program worked correctly.

package main

import "fmt"

func main() {
    var a int
    fmt.Printf("Enter an integer -> ")
    fmt.Scan(&a)
    fmt.Println("You entered:", a)
} 


Reading Text from console
 
Now, let's say that you need to read a text from the console. In that case we can use the function provided by the package bufio.

Here is an example:

package main

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

func main() {
    var mytext string
    var err error

    txtReader := bufio.NewReader(os.Stdin)

    fmt.Println("Enter some text ( Press Enter when done ) ")

    mytext, err = txtReader.ReadString('\n')

    if err == nil {
        fmt.Println("Here's what you wrote: \n", mytext)
    } else {
        fmt.Println("Error: ", err)
    }

}
As you can guess already, in the above example, we use the function NewReader of the package bufio, to return us a reader object that will help us read from the standard input i.e. the console.

We then use the ReadString function of the reader object and tell it that the input will terminate with a newline character.

We check for error and then we print the input text.

In the above example, the reader object returned by the function call bufio.NewReader()  has a read buffer of default size, which is 4096 bytes. If the text to input from console is larger than 4096 bytes, then we can use bufio.NewReaderSize() API to specify the number of bytes you desire to input.

No comments:

Post a Comment