how do I use my import package's struct as a type in go

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

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)

huangapple
  • 本文由 发表于 2013年8月15日 23:45:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/18256391.html
匿名

发表评论

匿名网友

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

确定