The equal sign = just assigns a new value to a variable which
needs to be declared in advance. The := operator does both steps
in one: Declare a variable of appropriate type and assign a value.
This is called short variabel declaration and it is explained in the 
Basics part of the Tour of Go.

In the first example stmt is not declared and thus is undeclared.
In the second example you do a short var decl for stmt and thus it
works.

V 

On Monday, 3 September 2018 08:03:24 UTC+2, sebastian andersen wrote:
>
> This code want's me to believe that I have not declared any of the 
> variables that I am currently trying to declare:
>
> func deleteRow() {
>     db, err := sql.Open("mysql", "root@/testshit")
>     checkErr(err)
>
>     // delete
>     stmt, err = db.Prepare("delete from userinfo where uid=?")
>     checkErr(err)
>
>     res, err = stmt.Exec(id)
>     checkErr(err)
>
>     affect, err = res.RowsAffected()
>     checkErr(err)
>
>     fmt.Println(affect)
>
>     db.Close()
> }
>
>
> Why is that? I don't understand that, it works fine in this context:
>
> func main() {
>     db, err := sql.Open("mysql", "root@/testshit")
>     checkErr(err)
>
>     // insert
>     stmt, err := db.Prepare("INSERT userinfo SET 
> username=?,departname=?,created=?")
>     checkErr(err)
>
>     res, err := stmt.Exec("astaxie", "dong", "2012-12-09")
>     checkErr(err)
>
>     id, err := res.LastInsertId()
>     checkErr(err)
>
>     fmt.Println(id)
>     // update
>     stmt, err = db.Prepare("update userinfo set username=? where uid=?")
>     checkErr(err)
>
>     res, err = stmt.Exec("astaxieupdate", id)
>     checkErr(err)
>
>     affect, err := res.RowsAffected()
>     checkErr(err)
>
>     fmt.Println(affect)
>
>     // query
>     rows, err := db.Query("SELECT * FROM userinfo")
>     checkErr(err)
>
>     for rows.Next() {
>         var uid int
>         var username string
>         var department string
>         var created string
>         err = rows.Scan(&uid, &username, &department, &created)
>         checkErr(err)
>         fmt.Println(uid)
>         fmt.Println(username)
>         fmt.Println(department)
>         fmt.Println(created)
>     }
>
>     // delete
>     stmt, err = db.Prepare("delete from userinfo where uid=?")
>     checkErr(err)
>
>     res, err = stmt.Exec(id)
>     checkErr(err)
>
>     affect, err = res.RowsAffected()
>     checkErr(err)
>
>     fmt.Println(affect)
>
>     db.Close()
>
> }
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to