如何将我的导入包的结构用作类型 [英] how do I use my import package's struct as a type in go

查看:67
本文介绍了如何将我的导入包的结构用作类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中工作,并使用数据库/ sql包。我想用包database / sql中声明的structDB作为我func的参数,所以我可以使用sql.Open()的返回值作为我的func参数。有可能吗?代码如下:

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
}

这段代码会抛出一个undefined:DB的错误。

This code throws a "undefined: DB" error.

推荐答案

您必须为导入的实体使用限定符 - name来自的包名称:

You must use a qualifier for imported entities - the package name from where the 'name' comes from:

func read(db *sql.DB, table string)

这篇关于如何将我的导入包的结构用作类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆