为什么我的特征数据库指针为零? [英] Why is my tiedot DB pointer nil?

查看:52
本文介绍了为什么我的特征数据库指针为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var myDB *db.DB

func init() {
    myDB, err := db.OpenDB("db")
    if err := myDB.Create("Feeds"); err != nil {}
    if err := myDB.Create("Votes"); err != nil {}
}

func idb() {
    for _, name := range myDB.AllCols() {
        fmt.Printf("I have a collection called %s\n", name)
    }    
}

func main() {
    idb()
}

我收到以下错误:

运行时错误:无效的内存地址或nil指针取消引用

runtime error: invalid memory address or nil pointer dereference

可能是因为myDBnil,但是为什么以及如何修复它,以便可以在init中设置myDB?

It is probably because myDB is nil, but why and how can I fix it so I can setup myDB in init?

请注意,如果我不使用全局变量就将所有内容都放到main中,那么它将起作用.

Note that if I just drop everything in main without using a global variable, it works.

推荐答案

简短变量声明

简短的变量声明使用以下语法:

A short variable declaration uses the syntax:

ShortVarDecl = IdentifierList ":=" ExpressionList .

这是带有初始化程序的常规变量声明的简写 表达式,但没有类型:

It is shorthand for a regular variable declaration with initializer expressions but no types:

"var" IdentifierList = ExpressionList .

myDB是局部init函数变量. :=是简短的变量声明.

myDB is a local init function variable. := is a short variable declaration.

myDB, err := db.OpenDB("db")

要更新软件包myDB变量,请写

To update package myDB variable, write,

var err error
myDB, err = db.OpenDB("db")

这篇关于为什么我的特征数据库指针为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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