Home >Backend Development >Golang >How to use keyboard input and output in Golang

How to use keyboard input and output in Golang

PHPz
PHPzOriginal
2023-04-11 09:14:012226browse

Golang is an efficient, modern language that is very convenient and practical when developing applications. This article will introduce how to use keyboard input and output in Golang.

1. Use the fmt package to output
The fmt package is a very commonly used package in the Golang standard library and provides many useful functions. This includes outputting content to the console. Using the fmt package to output is very simple, just call the fmt.Println() function:

package main

import "fmt"

func main() {
    fmt.Println("Hello, world!")
}

Run this code, we can see the output "Hello, world!" on the console.

2. Use bufio package for input
In addition to output, input is also a function we often need to use. Golang provides the bufio package, which can conveniently read user input. The following is a simple example of reading user input and output:

package main

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

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

In this code, we first imported the bufio package and os package, and created a reader variable in the main function for reading User input. Call the fmt.Print() function to output prompt information, wait for user input, and then use the reader.ReadString() function to read the user input. Finally, use the fmt.Println() function to output what the user entered.

3. Use third-party libraries to provide a better input/output experience

Although the above method is convenient, it only implements the most basic input and output functions. If a better user experience is needed, we can consider using third-party libraries. The following are two libraries worth recommending:

  1. termui
    termui is a terminal-based user interface library that provides many useful UI components that can make our Golang applications look more major. The following is a simple example implemented using termui:
package main

import (
    "github.com/gizak/termui/v3"
    "github.com/gizak/termui/v3/widgets"
)

func main() {
    err := termui.Init()
    if err != nil {
        panic(err)
    }
    defer termui.Close()

    p := widgets.NewParagraph()
    p.Text = "Enter text here:"
    p.SetRect(0, 0, 25, 3)

    tb := widgets.NewTextEdit()
    tb.SetRect(0, 3, 25, 5)

    termui.Render(p, tb)

    for e := range termui.PollEvents() {
        if e.Type == termui.KeyboardEvent {
            if e.ID == "q" {
                return
            }
            if e.ID == "<Enter>" {
                p.Text = "You entered " + tb.Text
                tb.SetText("")
            }
            termui.Render(p, tb)
        }
    }
}

In this example, we use termui's widgets.NewParagraph() and widgets.NewTextEdit() functions to create a paragraph and text edit box . The Render() function is used to render these components in the terminal. We also used the PollEvents() function to handle user input. When the user enters the Enter key, we use p.Text to update the prompt information and tb.Text to obtain the user input.

  1. gocui
    gocui is another library for creating terminal GUIs. It provides some common GUI components, such as windows, input boxes, buttons, etc. The following is a simple example implemented using gocui:
package main

import (
    "github.com/jroimartin/gocui"
)

func main() {
    g, err := gocui.NewGui(gocui.OutputNormal)
    if err != nil {
        panic(err)
    }
    defer g.Close()

    g.SetManagerFunc(func(g *gocui.Gui) error {
        if v, err := g.SetView("prompt", 0, 0, 25, 3); err != nil {
            if err != gocui.ErrUnknownView {
                return err
            }
            v.Title = "Enter text"
            v.Editable = true
            v.Wrap = true
            if _, err := g.Cursor(true); err != nil {
                return err
            }
            if err := g.SetKeybinding("prompt", gocui.KeyEnter, gocui.ModNone, enterHandler); err != nil {
                return err
            }
            if err := v.SetCursor(0, 0); err != nil {
                return err
            }
        }
        return nil
    })

    if err := g.MainLoop(); err != nil && err != gocui.ErrQuit {
        panic(err)
    }
}

func enterHandler(g *gocui.Gui, v *gocui.View) error {
    if _, err := g.View("prompt"); err != nil {
        return err
    }
    text := v.Buffer()
    if err := g.DeleteView("prompt"); err != nil {
        return err
    }
    if _, err := g.SetCurrentView(""); err != nil {
        return err
    }
    g.Update(func(g *gocui.Gui) error {
        return g.Close()
    })
    println("You entered: ", text)
    return nil
}

In this example, we use gocui's gocui.NewGui() function to create a GUI object, and use the g.SetManagerFunc() function Configure the GUI interface as an edit box. We also used the g.SetKeybinding() function to set the shortcut keys and implemented the enterHandler() function to handle user input.

Summary:
It is very convenient to use keyboard input and output in Golang. We can use the fmt and bufio packages in the Golang standard library to complete basic input and output operations. If we need a better user experience, we can also use the third-party libraries termui and gocui to create a terminal GUI.

The above is the detailed content of How to use keyboard input and output in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn