I am new at learning Go. I read that if I create a package and I use the install function that, that package will be available throughout my program. Yet after creating the following package and running the 'go install' command the package is not available to my program:
package person
import (
"fmt"
"time"
)
//Person struct
type Person struct {
FirstName, LastName string
Dob time.Time
Email, Location string
}
//PrintName method
func (p Person) PrintName() {
fmt.Printf("
%s %s
", p.FirstName, p.LastName)
}
//PrintDetails Method
func (p Person) PrintDetails() {
fmt.Printf("[Date of Birth: %s, Email: %s, Location: %s ]
", p.Dob.String(), p.Email,
p.Location)
}
and then creating the following main function either gives me 'syntax error: non-declaration statement outside function body' or it says the package is not found if I only use the package name which is what I learned I can do
package main
import (
"person"
)
p := Person {
FirstName : "Shiju",
LastName : "Varghese",
Dob : time.Date(1979, time.February, 17, 0, 0, 0, 0, time.UTC),
Email : "shiju@email.com",
Location : "Kochi",
}
p. PrintName()
p. PrintDetails()
What am I doing wrong please?
non declartion statement outside function body
refers to this part of your code
p := Person {
FirstName : "Shiju",
LastName : "Varghese",
Dob : time.Date(1979, time.February, 17, 0, 0, 0, 0, time.UTC),
Email : "shiju@email.com",
Location : "Kochi",
}
p. PrintName()
p. PrintDetails()
you need to put that insde some function, main
function for instance. also when you initiate a type, you need to refer it by its package name, for example, me:=person.Person{}
, that should take care of type Person not found
. If you are calling a type or function within the same package you don't need to do that. If its the same package, you will not need to import
it either.
the proper way to import a local package and use it would be
import person "./dirnameOfPackage"
func main(){
var p Person
p.FirstName = "yourName"
p.LastName = "lastname"
}
Hope this will help to solve your problem. If you want to declare your person outside of the function you should use var as well as you cant use methods outside of the functions
package main
import (
"person"
)
var p person.Person = Person {
FirstName : "Shiju",
LastName : "Varghese",
Dob : time.Date(1979, time.February, 17, 0, 0, 0, 0, time.UTC),
Email : "shiju@email.com",
Location : "Kochi",
}
func main(){
p.PrintName()
p.PrintDetails()
}