drcrc28428 2018-09-03 12:18
浏览 16
已采纳

找不到Go套件

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?

  • 写回答

3条回答 默认 最新

  • dongshengli6384 2018-09-03 14:29
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?