title: When should you initialize a new variable and when you should not?
body: <p>I'm looking at the code examples <a href="http://golang.org/pkg/database/sql/#DB.QueryRow" rel="nofollow">sql.query</a> and i'm a bit confused by the way the variables are initialized. As far as I understand the var keyword initialize the variable but if you already have a such variable it's better to 'reuse' it instead to reinitialize it. I'm aware that I might have misunderstood the golang specs so I hope this question would help me (and perhaps other folks) get it right.</p>
  
  <pre><code>  rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
      if err != nil {
              log.Fatal(err)
      }
      defer rows.Close()
      for rows.Next() {
              var name string
              if err := rows.Scan(&amp;name); err != nil {
                      log.Fatal(err)
              }
              fmt.Printf("%s is %d\n", name, age)
      }
      if err := rows.Err(); err != nil {
              log.Fatal(err)
      }
  </code></pre>
  
  <p>Why is the "name" variable initialized within the loop and not outside the loop ? (see below). Isn't it less performant to reinitialize it on each loop ? </p>
  
  <pre><code>//how I would do this
    rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
      if err != nil {
              log.Fatal(err)
      }
      defer rows.Close()
      var name string //outside the loop
      for rows.Next() {
  
              if err := rows.Scan(&amp;name); err != nil {
                      log.Fatal(err)
              }
              fmt.Printf("%s is %d\n", name, age)
      }
      if err := rows.Err(); err != nil {
              log.Fatal(err)
      }
  </code></pre>
  
  <p>or even better use a pointer</p>
  
  <pre><code>      rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
          if err != nil {
                  log.Fatal(err)
          }
          defer rows.Close()
          name := new(string) //pointer outside the loop
          for rows.Next() {
  
                  if err := rows.Scan(name); err != nil {
                          log.Fatal(err)
                  }
                  fmt.Printf("%s is %d\n", name, age)
          }
          if err := rows.Err(); err != nil {
                  log.Fatal(err)
          }
  </code></pre>