search
HomeBackend DevelopmentGolangUse the fmt.Println function to print output to the console

Use the fmt.Println function to print output to the console

Jul 25, 2023 am 08:46 AM
consolefmtprintlnprintout

Use the fmt.Println function to print output to the console

In the Go language, the fmt package provides a series of functions for formatting input and output. Among them, the fmt.Println function is one of the commonly used functions, through which we can print the content to the console.

Below, I will give some examples of using the fmt.Println function to help readers better understand its usage and functions.

  1. Print string

First, we can use the fmt.Println function to directly print a string. For example, if we want to print "Hello, World!", we can use the following code:

package main

import "fmt"

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

Execute the above code, the console will output:

Hello, World!
  1. Print variables

In addition to printing fixed strings, we can also print the values ​​of variables. For example, we define an integer variable x and assign it a value of 10. We can then print out the value of variable x using the fmt.Println function.

package main

import "fmt"

func main() {
    x := 10
    fmt.Println("x的值是:", x)
}

Execute the above code, the console will output:

x的值是: 10
  1. Printing multiple variables or strings

fmt.Println function also supports simultaneous printing Multiple variables or strings will be separated by spaces. For example, we define two string variables name and age and assign them corresponding values. Then, use the fmt.Println function to print the values ​​of these two variables.

package main

import "fmt"

func main() {
    name := "Alice"
    age := 20
    fmt.Println("姓名:", name, "年龄:", age)
}

Execute the above code, the console will output:

姓名: Alice 年龄: 20
  1. Formatted output

fmt.Println function also supports formatted output. For example, we can use the following code to print the value of the numeric variable pi to two decimal places:

package main

import "fmt"

func main() {
    pi := 3.14159
    fmt.Printf("π的值保留两位小数:%.2f
", pi)
}

Execute the above code, the console will output:

π的值保留两位小数:3.14
  1. Newline and not Line wrap

Finally, we can also control whether the fmt.Println function wraps the line after output. By default, this function adds a newline character to the output. If we want to output without line breaks, we can use the fmt.Print function. The following is an example:

package main

import "fmt"

func main() {
    fmt.Print("Hello, ")
    fmt.Println("World!") // 换行
    fmt.Print("Hello, ")
    fmt.Print("World!") // 不换行
}

Execute the above code, the console will output:

Hello, World!
Hello, World!

Through the above examples, we can see that the fmt.Println function prints output to the control in the Go language The role of the platform. Whether printing strings, variables, or formatting output, fmt.Println is a very convenient function.

I hope this article will help you understand and use the fmt.Println function. Enjoy the fun of Go programming!

The above is the detailed content of Use the fmt.Println function to print output to the console. 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
init Functions and Side Effects: Balancing Initialization with Maintainabilityinit Functions and Side Effects: Balancing Initialization with MaintainabilityApr 26, 2025 am 12:23 AM

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

Getting Started with Go: A Beginner's GuideGetting Started with Go: A Beginner's GuideApr 26, 2025 am 12:21 AM

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Go Concurrency Patterns: Best Practices for DevelopersGo Concurrency Patterns: Best Practices for DevelopersApr 26, 2025 am 12:20 AM

Developers should follow the following best practices: 1. Carefully manage goroutines to prevent resource leakage; 2. Use channels for synchronization, but avoid overuse; 3. Explicitly handle errors in concurrent programs; 4. Understand GOMAXPROCS to optimize performance. These practices are crucial for efficient and robust software development because they ensure effective management of resources, proper synchronization implementation, proper error handling, and performance optimization, thereby improving software efficiency and maintainability.

Go in Production: Real-World Use Cases and ExamplesGo in Production: Real-World Use Cases and ExamplesApr 26, 2025 am 12:18 AM

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

Custom Error Types in Go: Providing Detailed Error InformationCustom Error Types in Go: Providing Detailed Error InformationApr 26, 2025 am 12:09 AM

We need to customize the error type because the standard error interface provides limited information, and custom types can add more context and structured information. 1) Custom error types can contain error codes, locations, context data, etc., 2) Improve debugging efficiency and user experience, 3) But attention should be paid to its complexity and maintenance costs.

Building Scalable Systems with the Go Programming LanguageBuilding Scalable Systems with the Go Programming LanguageApr 25, 2025 am 12:19 AM

Goisidealforbuildingscalablesystemsduetoitssimplicity,efficiency,andbuilt-inconcurrencysupport.1)Go'scleansyntaxandminimalisticdesignenhanceproductivityandreduceerrors.2)Itsgoroutinesandchannelsenableefficientconcurrentprogramming,distributingworkloa

Best Practices for Using init Functions Effectively in GoBest Practices for Using init Functions Effectively in GoApr 25, 2025 am 12:18 AM

InitfunctionsinGorunautomaticallybeforemain()andareusefulforsettingupenvironmentsandinitializingvariables.Usethemforsimpletasks,avoidsideeffects,andbecautiouswithtestingandloggingtomaintaincodeclarityandtestability.

The Execution Order of init Functions in Go PackagesThe Execution Order of init Functions in Go PackagesApr 25, 2025 am 12:14 AM

Goinitializespackagesintheordertheyareimported,thenexecutesinitfunctionswithinapackageintheirdefinitionorder,andfilenamesdeterminetheorderacrossmultiplefiles.Thisprocesscanbeinfluencedbydependenciesbetweenpackages,whichmayleadtocomplexinitializations

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

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor