只有在条件为真时,我如何才能创建变量? [英] How do I create a variable in go only if a condition is true?

查看:193
本文介绍了只有在条件为真时,我如何才能创建变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在if块内创建一个变量,我以后不能使用它。如果我在if块之前创建了一个变量,并且if块的计算结果为false,那么我会得到一个变量已创建且未使用的错误。



我确定这是设计的,我试图做我不应该做的事情,但是我想要做的背后的逻辑对我来说很有意义。如果网址中有页面信息,我想在稍后的sql语句中使用它,但是如果URL中没有页面信息,那么我不需要这些变量。



http://pastebin.com/QqwpdM1d



编辑:这是代码:

  var pageID string 
var offset int
如果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。打开(mysql,conn)
推迟db.Close()
if err!= nil {
log.Fatal(err)
}
var rows * sql.Rows
如果偏移!= 0 {
// ...
}


<如果你在之前声明一个变量if 语句,并且你在语句中使用它,如果块,它无关紧要,它不是一个编译时错误。



你遇到的错误是如果块没有使用中的声明变量。你的代码:

  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)
}
}

内如果没有分配给之前声明的 pageID ,但是您正在使用< a href =https://golang.org/ref/spec#Short_variable_declarations =nofollow>短变量声明 := 它创建一个新的变量,隐藏在外部块中创建的变量,并且只有在结束时才有效(如果块)(它的作用域结束于最内层包含块的末尾) 。

解决方案是(你最想要的)简单地使用赋值 = (它赋值给现有的变量):

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






为了理解,请看这个例子:

  i:= 1 
fmt.Println(Outer:,i)
{
i:= 2 // Short var decl:创建一个新的i,映射外部
fmt.Println(Inner :,i)
}
fmt.Println(Outer again:,i)

输出(在 Go Playground 上试用):

 外部:1 
内部:2
外部:1


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

这篇关于只有在条件为真时,我如何才能创建变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆