dongshi6529 2016-05-03 02:06
浏览 195
已采纳

在没有选择器错误的情况下使用软件包

I'm using this config library called Viper

In my main I have this:

viper.SetConfigName("development")
viper.AddConfigPath("config/settings/")
err := viper.ReadInConfig()
if err != nil {
    fmt.Println("viper config read error %v", err)
}

I then have a struct that takes a viper as parameter:

type MyConfig struct {
  v *viper.Viper
}

In my main I have a function that returns this MyConfig like:

func NewMyConfig(v *viper.Viper) *MyConfig {
    return &MyConfig{v: v}
}

I am getting this error:

./main.go:55: use of package viper without selector

Not sure what I should be doing?

  • 写回答

1条回答 默认 最新

  • dounanyin3179 2016-05-03 03:22
    关注

    When you import a package like

    import "github.com/spf13/viper"
    

    the package name (which is viper in this case) will be available to you as a new identifier. You may use this identifier to construct qualified identifiers to refer to exported identifiers of the package (identifiers that start wtih an uppercase letter).

    The package name itself cannot be used by itself. The line that gives you error:

    myConfig = NewMyConfig(&viper)
    

    You used package name viper without specifying what exported identifier you want to refer to from the package.

    You want to use your NewMyConfig() function to obtain a pointer to a new value of your MyConfig struct. Your NewMyConfig() function expects a value of *viper.Viper. Since the viper.Viper struct contains unexported fields, you can just create it like &viper.Viper{}, but the viper package exports a function viper.New() which can be used to obtain a pointer to a new, initialized viper.Viper value. You may use it like:

    vp := viper.New()
    myConfig = NewMyConfig(vp)
    

    Note that the viper package declares an internal, global, unexported viper.Viper "instance". There are many exported functions that match methods of the viper.Viper type. These "matching" functions work on the global, unexported viper.Viper instance. So you may choose to use all the exported global functions of the viper package, or create your own Viper instance and then keep using its methods afterwards.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)