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

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

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
}

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:

确定