英文:
Package selection in Go
问题
我正在尝试编写一个从数据库中获取状态的应用程序,但是我似乎在语言的一个非常基本的原则上遇到了困难。我已经编写了程序,但由于错误use of package time not in selector
,它无法编译。
这是一个非常基本的示例(来自play.golang.org的测试环境):
package main
import (
"fmt"
"time"
)
func main() {
s_str := time.Now()
fmt.Println(printT(s_str))
}
func printT(t time) time {
return t.Add(100)
}
不幸的是,我发现在线文档和帮助文档都有些不足。我的理解是,import
语句应该像C++一样为整个程序包括库,对吗?
英文:
I'm trying to write an application to pull status from a database, but I seem to be getting stuck on a really basic principle of the language. I have the program written, but it doesn't compile due to the error use of package time not in selector
.
A really basic example (from play.golang.org's own test environment)
package main
import (
"fmt"
"time"
)
func main() {
s_str := time.Now()
fmt.Println( printT(s_str) )
}
func printT(t time) time {
return t.Add(100)
}
Unfortunately, I've found documentation and helpdocs online a bit wanting. My understanding is that the import
statement should include the library for the entire program like in C++ correct?
答案1
得分: 25
你必须在导入的类型或变量前加上你在导入中给包起的名字(这里你使用的是默认名字,即"time")。这就是你对函数Now
所做的操作,但你也必须对类型做同样的操作。
所以类型不是"time",而是"time.Time"(也就是在你用名字"time"导入的包中声明的类型"Time")。
将你的函数改为:
func printT(t time.Time) time.Time {
return t.Add(100)
}
至于你的第二个问题:不,import
语句只包含当前文件的库,而不是整个程序的库。
英文:
You have to prefix the imported types or variables with the name you gave to the package in the import (here you use the default name, that is "time"). That's what you did for the function Now
but you have to do it also for the types.
So the type isn't time
but time.Time
(that is : the type Time
that is declared in the package you import with the name "time"
).
Change your function to
func printT(t time.Time) time.Time {
return t.Add(100)
}
And for your second question : No, the import
statement doesn't include the library for the entire program but only for the current file.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论