Variable Scope in Go
In Go, variables must be declared within a specific scope. When you declare a variable inside an if...else statement, its scope is limited to that statement. This means that the variable cannot be used outside of the statement.
Consider the following code:
if strings.EqualFold(r.Method, "GET") || strings.EqualFold(r.Method, "") { req, er := http.NewRequest(r.Method, r.Uri, b) } else { req, er := http.NewRequest(r.Method, r.Uri, b) }
In this code, the variables req and er are declared inside the if...else statement. This means that they can only be used within that statement. Outside of the statement, the variables are undefined.
To solve this issue, you can declare the variables outside of the if...else statement, as shown below:
var req *http.Request var er error if strings.EqualFold(r.Method, "GET") || strings.EqualFold(r.Method, "") { req, er = http.NewRequest(r.Method, r.Uri, b) } else { req, er = http.NewRequest(r.Method, r.Uri, b) }
Now, the variables req and er are declared outside of the if...else statement, so they can be used throughout the function.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!