仅当条件为真时,如何在go中创建变量?

If I create a variable inside an if block, I can't use it later on. If I create a variable before the if block and the if block evaluates to false, I get a "variable created and not used" error.

I'm certain that this is by design and I'm trying to do something I shouldn't, but the logic behind what I'm trying to do makes sense to me. If there is page info in the url, I want to use it in a sql statement later on, but if there isn't page info in the url, then I don't need those variables.

http://pastebin.com/QqwpdM1d

Edit: here's the code:

var pageID string
var offset int
if len(r.URL.Path) > len("/page/") {
    pageID := r.URL.Path[len("/page/"):]
    offset, err := strconv.Atoi(pageID)
    if err != nil {
        log.Fatal(err)
    }
}
conn := "..."
db, err := sql.Open("mysql", conn)
defer db.Close()
if err != nil {
    log.Fatal(err)
}
var rows *sql.Rows
if offset != 0 {
    // ...
}

If you declare a variable before an if statement and you use it inside the if block, it doesn't matter what the condition evaluates to, it is not a compile time error.

The error in you case is that you don't use the declared variable inside the if block. Your code:

var pageID string
var offset int
if len(r.URL.Path) > len("/page/") {
    pageID := r.URL.Path[len("/page/"):]
    offset, err := strconv.Atoi(pageID)
    if err != nil {
        log.Fatal(err)
    }
}

Inside the if you are not assigning to the previously declared pageID, but you are using short variable declaration := which creates a new variable, shadowing the one created in the outer block, and it is in effect only at the end of the if block (its scope ends at the end of the innermost containing block).

Solution is (what you most likely wanted to) simply use assignment = (which assigns value to the existing variable):

    pageID = r.URL.Path[len("/page/"):]

To make it understand, see this example:

i := 1
fmt.Println("Outer:", i)
{
    i := 2 // Short var decl: creates a new i, shadowing the outer
    fmt.Println("Inner:", i)
}
fmt.Println("Outer again:", i)

Output (try it on the Go Playground):

Outer: 1
Inner: 2
Outer again: 1