英文:
Undefined Error in Golang
问题
我有以下的结构:
/*gotime.go*/
package gotime
type Now struct {
dnow int
ynow int
mnow time.Month
}
是否有这样的函数:
/*gotime.go*/
func (n Now) DayNow() int {
n.dnow = time.Now().Day()
return n.dnow
}
当我想调用这个包时,我得到以下错误:
/*main.go*/
package main
import (
"fmt"
"./gotime"
)
blah := Now
fmt.Println(blah.DayNow())
我得到了以下错误:
# command-line-arguments
.\main.go:5: imported and not used: "_/C_/Users/ali/Desktop/test/gotime"
.\main.go:10: undefined: Now
你可以在GitHub上查看整个包:
链接 这个包的链接
我该如何解决这个问题?
英文:
I have the following structure:
/*gotime.go*/
package gotime
type Now struct {
dnow int
ynow int
mnow time.Month
}
And is there a function like:
/*gotime.go*/
func (n Now) DayNow() int {
n.dnow = time.Now().Day()
return n.dnow
}
I'm getting the following error when I want to call this package:
/*main.go*/
package main
import (
"fmt"
"./gotime"
)
blah := Now
fmt.Println(blah.DayNow())
I get errors:
# command-line-arguments
.\main.go:5: imported and not used: "_/C_/Users/ali/Desktop/test/gotime"
.\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
是一个结构体,你需要使用结构体复合字面量来创建该类型的值。
另外,由于它来自另一个包,你需要使用限定名称:
blan := gotime.Now{}
请注意,你需要在包名之前加上前缀:package-name.foo。
另外,由于你正在修改它,你应该/需要使用指针接收器:
func (n *Now) DayNow() int {
n.dnow = time.Now().Day()
return n.dnow
}
英文:
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:
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:
func (n *Now) DayNow() int {
n.dnow = time.Now().Day()
return n.dnow
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论