Home  >  Article  >  Backend Development  >  Use the fmt.Scan function to read formatted data from the input and assign it to a variable

Use the fmt.Scan function to read formatted data from the input and assign it to a variable

PHPz
PHPzOriginal
2023-07-24 11:22:551257browse

Use the fmt.Scan function to read formatted data from the input and assign it to a variable

In the Go language, the fmt package provides some functions for formatting input and output. Among them, the fmt.Scan function can read formatted data from standard input and assign the read data to the specified variable.

Using the fmt.Scan function to read input is very simple. You only need to introduce the "fmt" package and then call the Scan function. The following is a sample code:

package main

import "fmt"

func main() {
    var name string
    var age int

    fmt.Printf("请输入您的姓名: ")
    fmt.Scan(&name)
    fmt.Printf("请输入您的年龄: ")
    fmt.Scan(&age)

    fmt.Printf("您的姓名是:%s
", name)
    fmt.Printf("您的年龄是:%d
", age)
}

In the above code, we define two variables name and age to store the entered name and age. Then, read the input value by calling the fmt.Scan function, and use the & operator to assign the read value to the corresponding variable.

Run the above code, you will see the following output:

请输入您的姓名: John
请输入您的年龄: 28
您的姓名是:John
您的年龄是:28

Through this example, we can see that reading formatted input using the fmt.Scan function is very simple. Just pass the address of the variable to the Scan function through the & operator, and it will automatically assign the value to the variable after the user inputs.

But it should be noted that when the input is read using the fmt.Scan function, it will be separated based on spaces or newlines. So if you want to read multiple values ​​without spaces or newlines between the values, consider using the Scanner type from the bufio package. The Scan method of the Scanner type can read an entire line of input and separate the input based on spaces.

To summarize, by using the fmt.Scan function, we can easily read formatted data from the input and assign it to the corresponding variable. This is a very simple and practical function that can help us better handle user input. Hope this article is helpful to you.

The above is the detailed content of Use the fmt.Scan function to read formatted data from the input and assign it to a variable. 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