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.
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!
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
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
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
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!