Use the fmt.Sscan function to read formatted data from a string and assign it to a variable, and return the number of read parameters
In the Go language, the fmt package provides a series of functions to Convert strings to and from other data types. Among them, the fmt.Sscan function can read formatted data from a string and assign it to the corresponding variable.
The function is defined as follows:
func Sscan(str string, a ...interface{}) (n int, err error)
The parameters of the Sscan function include A string and a series of variables to receive the data. The return value includes the number of parameters read n and the possible error err.
Below we use an example to illustrate how to use the fmt.Sscan function.
package main import ( "fmt" ) func main() { str := "123 456 789" var a, b, c int num, err := fmt.Sscan(str, &a, &b, &c) if err != nil { fmt.Println("读取数据失败") return } fmt.Println("读取的参数个数:", num) fmt.Println("a:", a) fmt.Println("b:", b) fmt.Println("c:", c) }
Run the above code, the output result is as follows:
Number of parameters read: 3
a: 123
b: 456
c: 789
As you can see from the code, we first define a string str and separate three integers with spaces. Then, by calling the fmt.Sscan function, these three integers are assigned to the three variables a, b, and c in sequence.
After calling the function, we determine whether the reading is successful by judging the value of err. If err is not nil, reading data failed. Next, we output the number of parameters read and the value of each variable.
As shown in the example, the fmt.Sscan function can flexibly read data according to the format in the string and assign the read data to the corresponding variables. This is very useful in actual development, as it can easily obtain the required data from user input, file reading and other channels.
To sum up, the fmt.Sscan function is a method of quickly parsing strings in the Go language. Through this function, the formatted data in the string can be easily read and assigned to the corresponding variables, thereby Meet our actual needs in programming.
The above is the detailed content of Use the fmt.Sscan function to read formatted data from a string and assign it to a variable, and return the number of parameters read.. For more information, please follow other related articles on the PHP Chinese website!