Golang,指针,函数

huangapple go评论92阅读模式
英文:

Golang, Pointers, Functions

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对Golang和编译型、静态类型编程都很陌生,之前的经验都是使用Python。

这种范式转变既令人沮丧(程序很少能编译通过),又令人满意,因为我终于开始理解之前对我来说很陌生的概念(垃圾回收、指针、作用域)。

有人能从概念层面上解释一下为什么这个程序无法编译,以及如何修复语法?我只是想查询数据库并打印结果:

package main

import (
	"database/sql"
	"log"

	_ "github.com/denisenkom/go-mssqldb"
)

func main() {

	db, err := sql.Open("sqlserver", "odbc:server=myServer;user id=myName;password=myPassword;")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	q()
}

func q() {

	var (
		id   int
		name string
	)

	rows, err := db.Query("SELECT id, name FROM myTable")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	for rows.Next() {
		err := rows.Scan(&id, &name)

		if err != nil {
			log.Fatal(err)
		}
		log.Println(id, name)
	}
	err = rows.Err()
	if err != nil {
		log.Fatal(err)
	}

}

我得到的错误是:

undefined: db in db.Query

当我将逻辑放在main函数中的q()函数内时,查询是有效的——我猜这是因为函数具有“局部”作用域(这个术语正确吗?),我需要像在main函数中那样定义db对象。

如果是这样的话,我如何在不重复建立数据库连接的情况下运行q()函数呢?这就是“指针”发挥作用的地方吗?此外,我仍然不确定这里的“&”符号是做什么用的:

err := rows.Scan(&id, &name)

谢谢。

英文:

I'm new to Golang and to compiled, statically-typed programming in general. All my prior experience has been with Python.

This paradigm shift has been both frustrating (programs rarely compile) and rewarding as I'm finally getting my head around many concepts that were previously foreign to me (garbage collection, pointers, scope).

Can someone explain to me on a conceptual level why this program won't compile and the syntax to fix it? I'm simply trying to query a DB and print the results:

package main

import (
	"database/sql"
	"log"

	_ "github.com/denisenkom/go-mssqldb"
)

func main() {

	db, err := sql.Open("sqlserver", "odbc:server=myServer;user id=myName;password=myPassword;")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	q()
}

func q() {

	var (
		id   int
		name string
	)

	rows, err := db.Query("SELECT id, name FROM myTable")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	for rows.Next() {
		err := rows.Scan(&id, &name)

		if err != nil {
			log.Fatal(err)
		}
		log.Println(id, name)
	}
	err = rows.Err()
	if err != nil {
		log.Fatal(err)
	}

}

The error I'm getting is:

undefined: db in db.Query

The query works when I put the logic inside q() in the main function - I'm assuming this is because functions have "local" scope (is that the correct terminology?) and I need to define the db object as I have in the main function.

If this is the case - how do I run the q() function without repeating myself in establishing the db connection? Is this where "pointers" come in? Also, I'm still uncertain as to what the ampersands are doing here:

 err := rows.Scan(&id, &name)

Thanks

答案1

得分: 3

db变量在main函数的作用域中定义,所以你的q函数无法"看到"它。你需要将其作为指针传递给q方法。像这样:

func q(db *sql.DB) {
   ...
}

main函数中,你的db变量已经是一个指向sql.DB结构体的指针,所以你只需要在main函数中调用q(db),它就会起作用。

英文:

db var is defined at main func scope, so your q func don't "see" it. You have to pass as pointer to q method. Something like that:

func q(db *sql.DB) {
   ...
}

Your db var in main is already a pointer to sql.DB struct, so you just have to do q(db) call in main func and it'll work.

答案2

得分: 2

如其他人所提到的,问题在于变量db在函数main中声明,而你试图在q函数中访问该变量。你有两个解决这个问题的选项:

1)将变量db声明为全局变量,放在main函数外部,像这样:

package main

import (
    "database/sql"
    "log"
    _ "github.com/denisenkom/go-mssqldb"
)

var db *sql.DB

func main() {
    db, err = sql.Open("sqlserver", "odbc:server=myServer;user id=myName;password=myPassword;")
    // ...
}

需要注意的重要事项是赋值操作符(=)用于给全局变量赋值,因为如果使用短变量声明(:=),那么会创建一个局部变量db

2)你可以将db指针作为参数传递给q函数,像这样:

package main

import (
    "database/sql"
    "log"
    _ "github.com/denisenkom/go-mssqldb"
)

func main() {
    db, err := sql.Open("sqlserver", "odbc:server=myServer;user id=myName;password=myPassword;")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    q(db)
}

func q(db *sql.DB) {
    var (
        id   int
        name string
    )
    // ...
}

以上是翻译好的内容,请确认是否满意。

英文:

As others mentioned, the problem is the variable db is declared in function main and you are trying to access that variable in q function. You have two options to solve this problem:

  1. Declare the variable db as a global variable outside the main function like this:

As others mentioned, the problem is the variable db is declared in function main and you are trying to access that variable in q function. You have two options to solve this problem:

  1. Declare the variable db as a global variable outside the main function like this:

    package main

    import (
    "database/sql"
    "log"
    _ "github.com/denisenkom/go-mssqldb"
    )

    var db *sql.DB

    func main() {

    db, err = sql.Open("sqlserver", "odbc:server=myServer;user id=myName;password=myPassword;")
    .
    .
    .
    .

The important thing to notice is the assignment (= instead of :=) operator used to assign value to the global variable. Because if you use the short variable declaration := then it would create a local db variable.

  1. You can pass the db pointer as a parameter to the function q like this:

    package main

    import (
    "database/sql"
    "log"
    _ "github.com/denisenkom/go-mssqldb"
    )
    func main() {

     db, err := sql.Open("sqlserver", "odbc:server=myServer;user id=myName;password=myPassword;")
     if err != nil {
       log.Fatal(err)
     }
     defer db.Close()
    
     q(db)
    

    }

    func q(db *sql.DB) {

     var (
         id   int
         name string
     )
    

    .
    .
    .
    .

huangapple
  • 本文由 发表于 2017年2月17日 06:22:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/42285817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定