search
HomeBackend DevelopmentGolangHow to use keyboard input and output in Golang

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)
        }
    }
}</enter>

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
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)