Home > Article > Backend Development > How does golang handle input?
Golang's method of processing input: 1. [fmt.Scan] interactively accepts input and uses spaces to segment words; 2. [fmt.Scanln] specifies the variable name and number of variables to receive input; 3. [fmt .Scanf] You need to specify the input format and directly filter out the unnecessary parts.
Golang’s method of processing input:
1. fmt.Scan
fmt.Scan
Interactively accepts input and uses spaces to segment words. When calling the Scan function, you must specify the variable name and number of variables to receive input.
The Scan function will not return until all the specified variables are received, and the carriage return character cannot make it return in advance.
fmt.Println("Please enter the firstName and secondName: ") fmt.Scan(&afirstName, &asecondName) fmt.Printf("firstName is %s, secondName is %s\n", afirstName, asecondName)
The results are as follows:
Please enter the firstName and secondName: zz rr firstName is zz, secondName is rr
2. fmt.Scanln
##ScanlnWhen calling, you must also specify the input to be received. Variable name and variable number.
\ n will cause the function to return early and assign variables that have not yet received values when returning to empty.
fmt.Println("Please enter the firstName and secondName: ") fmt.Scanln(&bfirstName, &bsecondName) fmt.Printf("firstName is %s, secondName is %s\n", bfirstName, bsecondName)The results are as follows:
Please enter the firstName and secondName: zr firstName is zr, secondName is
3. fmt.Scanf
UsingScanf to process input is more flexible. kind of processing method.
fmt.Println("Please enter the firstName and secondName: ") fmt.Scanf("//%s\n%s", &cfirstName, &csecondName) fmt.Printf("firstName is %s, secondName is %s", cfirstName, csecondName)The results are as follows: 1) In this scenario, when receiving input, the unnecessary parts "//" and "\n" are filtered out, and the received ones are useful Two strings zz and rr.
Please enter the firstName and secondName: //zz rr firstName is zz, secondName is rr2) If the input does not conform to the specified format, starting from the non-conformity point, the subsequent variable values will be empty.
Please enter the firstName and secondName: //zr ui firstName is zr, secondName is
Related learning recommendations:
The above is the detailed content of How does golang handle input?. For more information, please follow other related articles on the PHP Chinese website!