在Golang中出现了未定义的错误。

huangapple go评论124阅读模式
英文:

Undefined Error in Golang

问题

我有以下的结构:

  1. /*gotime.go*/
  2. package gotime
  3. type Now struct {
  4. dnow int
  5. ynow int
  6. mnow time.Month
  7. }

是否有这样的函数:

  1. /*gotime.go*/
  2. func (n Now) DayNow() int {
  3. n.dnow = time.Now().Day()
  4. return n.dnow
  5. }

当我想调用这个包时,我得到以下错误:

  1. /*main.go*/
  2. package main
  3. import (
  4. "fmt"
  5. "./gotime"
  6. )
  7. blah := Now
  8. fmt.Println(blah.DayNow())

我得到了以下错误:

  1. # command-line-arguments
  2. .\main.go:5: imported and not used: "_/C_/Users/ali/Desktop/test/gotime"
  3. .\main.go:10: undefined: Now

你可以在GitHub上查看整个包:

链接 这个包的链接

我该如何解决这个问题?

英文:

I have the following structure:

  1. /*gotime.go*/
  2. package gotime
  3. type Now struct {
  4. dnow int
  5. ynow int
  6. mnow time.Month
  7. }

And is there a function like:

  1. /*gotime.go*/
  2. func (n Now) DayNow() int {
  3. n.dnow = time.Now().Day()
  4. return n.dnow
  5. }

I'm getting the following error when I want to call this package:

  1. /*main.go*/
  2. package main
  3. import (
  4. "fmt"
  5. "./gotime"
  6. )
  7. blah := Now
  8. fmt.Println(blah.DayNow())

I get errors:

  1. # command-line-arguments
  2. .\main.go:5: imported and not used: "_/C_/Users/ali/Desktop/test/gotime"
  3. .\main.go:10: undefined: Now

You can look at all of the package on GitHub:

Link for this package

How can I solve this problem?

答案1

得分: 5

由于Now是一个结构体,你需要使用结构体复合字面量来创建该类型的值。

另外,由于它来自另一个包,你需要使用限定名称

  1. blan := gotime.Now{}

请注意,你需要在包名之前加上前缀:package-name.foo

另外,由于你正在修改它,你应该/需要使用指针接收器:

  1. func (n *Now) DayNow() int {
  2. n.dnow = time.Now().Day()
  3. return n.dnow
  4. }
英文:

Since Now is a struct, you need a struct Composite literal to create a value of that type.

Also since it is from another package, you need the Qualified name:

  1. blan := gotime.Now{}

Notice that you have to prepend the package name: package-name.foo.

Also since you are modifying it, you should / need to use a pointer receiver:

  1. func (n *Now) DayNow() int {
  2. n.dnow = time.Now().Day()
  3. return n.dnow
  4. }

huangapple
  • 本文由 发表于 2015年5月14日 16:43:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/30232935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定