即使初始化后变量为零[duplicate]

问题描述 投票:-1回答:1

这里是代码config / config.go

const PROJECT_ID = "projectid"

var Ctx = context.Background()

var DSClient *datastore.Client

type Logger struct {
    Pkg string
}

func (l *Logger) Error(v ...interface{}) {
    log.Print("Error|", l.Pkg, ": ", v)
}

func (l *Logger) Info(v ...interface{}) {
    log.Print("Info|", l.Pkg, ": ", v)
}
var propFile = "${env}.properties"
var Props *properties.Properties

func init(){
    Props = properties.MustLoadFile(propFile, properties.UTF8)
    DSClient, err := datastore.NewClient(Ctx, PROJECT_ID)
    if err != nil {
        log.Fatal("Couldn't connect to DataStore: ", err)
    }
    log.Print("DataStore Client: ", DSClient)
}

index / index.go

    import (
    ...
    "github.com/shwetanka19/project/internal/config"
)
    urs := [] user.User{}
    q := datastore.NewQuery("users").Filter("email=", greq.Email).Limit(1)
    logger.Info("Now Client: ", config.DSClient)
    keys, err := config.DSClient.GetAll(config.Ctx, q, &urs)

日志

DataStore Client: &{0xc000010840 0xc000119d40 projectid}

[Now Client:  <nil>]

为什么客户端在初始化后现在为零?在API调用期间会调用index.go中的代码。服务器启动时调用config时。

go google-cloud-datastore
1个回答
1
投票

执行时

DSClient, err := datastore.NewClient(Ctx, PROJECT_ID)

您创建一个new变量DSClient,该变量隐藏了另一个变量。您只需要将其更改为:

var err error
DSClient, err = datastore.NewClient(Ctx, PROJECT_ID)
© www.soinside.com 2019 - 2024. All rights reserved.