4

为什么 main 中调用包中可导出变量提示未

 1 year ago
source link: https://studygolang.com/articles/35715
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

为什么 main 中调用包中可导出变量提示未

fmt_return · 大约5小时之前 · 34 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    

被导入包:

package utils

import (
    "github.com/elastic/go-elasticsearch/v6"
    "log"
)

var EsClient *elasticsearch.Client

func init() {
    host := Cfg.Section("es").Key("host").String()
    if host == "" {
        log.Fatal("es Host 未设置")
    }

    cfg := elasticsearch.Config{
        Addresses: []string{host},
    }

    EsClient, err := elasticsearch.NewClient(cfg)
    if err != nil {
        log.Fatal("连接失败", err)
    }

    _, err = EsClient.Info()
    if err != nil {
        log.Fatalf("连接出错:"+host, err)
    }

    fmt.Println(EsClient) // &{0xc000166000 0xc000162000}
}

main.go

package main

import (
    "data_push/utils"
    "fmt"
)

func main() {
   fmt.Println(utils.EsClient) // 结果为 nil
}

main 函数中输出 utils 包中 EsClient 变量,结果为 nil,但是 utils 包中初始化后值不为 nil,这是什么原因呢?


有疑问加站长微信联系(非本文作者)

280

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK