英文:
how do I use my import package's struct as a type in go
问题
我正在使用Go语言的"database/sql"包进行项目开发。我想将"database/sql"包中声明的结构体"DB"作为我的函数参数,这样我就可以使用sql.Open()的返回值作为我的函数参数。这样做是可行的吗?以下是代码:
package main
import (
"database/sql"
"fmt"
_ "github.com/Go-SQL-Driver/MySQL"
)
func main() {
var table string = "tablename"
db, err := sql.Open("mysql", "user:password@/dbname")
// 从数据库中读取数据
read(db, table)
}
func read(db *DB, table string) {
// 读取数据
}
这段代码会报错"undefined: DB"。
英文:
I'm working in a project and using "database/sql" package in go. And I want to use struct "DB" that declare in package "database/sql" as an argument to my func, so I can use the return value by sql.Open() and as my func's argument. Was it possible? Codes are below:
package main
import (
"database/sql"
"fmt"
_ "github.com/Go-SQL-Driver/MySQL"
)
func main() {
var table string = "tablename"
db, err := sql.Open("mysql", "user:password@/dbname")
// read data from database
read(db, table)
}
func read(db *DB, table string) {
// read
}
This code throws a "undefined: DB" error.
答案1
得分: 19
你必须为导入的实体使用限定符 - 来自于哪个包的“name”:
func read(db *sql.DB, table string)
英文:
You must use a qualifier for imported entities - the package name from where the 'name' comes from:
func read(db *sql.DB, table string)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论