Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Package selection in Go

Tags:

go

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?

like image 738
Jacobm001 Avatar asked Sep 13 '13 15:09

Jacobm001


1 Answers

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.

like image 176
Denys Séguret Avatar answered Nov 13 '22 00:11

Denys Séguret