Home Backend Development Golang How to print in golang

How to print in golang

Apr 05, 2023 pm 01:50 PM

Use the function in the fmt package to print

The Go language is a statically typed, compiled language developed by Google. Its syntax is concise and clear, and its concurrency capabilities are powerful, so it has attracted much attention in recent years. . There are many built-in functions in the Go language, including printing functions. In this article, we will learn how to print using functions of fmt package in Go language.

1. fmt package

In the Go language, the fmt package is a very powerful package that implements the function of formatted input and output. The fmt package can easily perform printing operations. It can print values ​​of various data types and also set formats. The fmt package also provides some other functions such as Scan, Scanln and Scanf for reading data from standard input. Let's take a look at how to use the functions of the fmt package for printing.

2. The Print function in the fmt package

The Print function in the fmt package can print data to the standard output. The code below shows how to use the Print function to print a string to the console.

package main

import "fmt"

func main() {
   fmt.Print("Hello, world!")
}
Copy after login

In the above code, the Print function of the fmt package is called and the string "Hello, world!" is printed to the console. The printing here will not automatically wrap at the end. If you want to add a newline character at the end, you can use the println function.

package main

import "fmt"

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

3. The Printf function in the fmt package

The Printf function of the fmt package can print a formatted string to the standard output. The first parameter of the Printf function is the format string, and the subsequent parameters are the content to be filled. The code below demonstrates how to print a formatted string using the Printf function.

package main

import "fmt"

func main() {
   name := "Tom"
   age := 32
   fmt.Printf("My name is %s,I'm %d years old.", name, age)
}
Copy after login

In the above code, the formatted string in sprintf is "My name is %s, I'm %d years old.", where the % character is followed by a letter, indicating this string The type of data that needs to be populated. For example, %s represents the string type, and %d represents the integer type. In this example, the first %s will be replaced by the value of the string variable name, and the second %d will be replaced by the value of the integer variable age.

4. Other functions in the fmt package

There are other functions in the fmt package, such as Sprintf function, Fprint function and Fprintf function. They are similar to Print and Printf functions, but use The method or output target is different. Below we briefly introduce these functions.

  1. Sprintf function

. The Sprintf function is similar to the Printf function, but it does not output a formatted string to the console, but returns a string. The code below demonstrates how to use the Sprintf function.

package main

import "fmt"

func main() {
   name := "Tom"
   age := 32
   // 将格式化字符串保存到变量str中
   str := fmt.Sprintf("My name is %s,I'm %d years old.", name, age)
   // 输出变量str中的字符串
   fmt.Print(str)
}
Copy after login
  1. Fprint function

The first parameter of the Fprint function is an io.Writer (interface), indicating the output destination. It can output formatted strings to files, network connections, standard output, etc., just pass in the appropriate io.Writer. For example, the following code demonstrates how to output a formatted string to a file.

package main

import (
    "fmt"
    "os"
)

func main() {
    f, err := os.Create("test.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()
    // 将格式化字符串输出到文件中
    fmt.Fprint(f, "Hello, world!")
}
Copy after login

In the above code, the os.Create function creates a file named test.txt, and the formatted string "Hello, world!" is written to this file.

  1. Fprintf function

The Fprintf function is similar to the Printf function, but it does not output the formatted string to the console, but outputs it to a file or network Connections, standard output, etc. locations. Similar to the Fprint function, you just need to pass in the appropriate io.Writer. The code below demonstrates how to output a formatted string to a file.

package main

import (
    "fmt"
    "os"
)

func main() {
    f, err := os.Create("test.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()
    name := "Tom"
    age := 32
    // 将格式化字符串输出到文件中
    fmt.Fprintf(f, "My name is %s,I'm %d years old.", name, age)
}
Copy after login

In the above code, the fmt.Fprintf function outputs the formatted string to the file, and the variables in the formatted string "My name is %s, I'm %d years old." are replaced with corresponding values.

Summary:

In the Go language, the functions of the fmt package can easily perform printing operations. They can print values ​​of various data types and can also perform formatting operations. By using some other functions, such as Sprintf function, Fprint function and Fprintf function, the output content can be made more flexible and diverse. Proficient in the functions in the fmt package can enable us to develop Go language programs more effectively.

The above is the detailed content of How to print in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

How do you use table-driven tests in Go? How do you use table-driven tests in Go? Mar 21, 2025 pm 06:35 PM

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a

Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications? Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications? Mar 25, 2025 am 11:17 AM

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

How do you specify dependencies in your go.mod file? How do you specify dependencies in your go.mod file? Mar 27, 2025 pm 07:14 PM

The article discusses managing Go module dependencies via go.mod, covering specification, updates, and conflict resolution. It emphasizes best practices like semantic versioning and regular updates.

See all articles