导入的其他包中的结构体未定义。

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

Imported struct from other package is undefined

问题

这是我的初学者问题。我在models/model.go中有这个结构体。

package models

import (
  "time"
  "gopkg.in/mgo.v2/bson"
)

type Horse struct {
  Id          bson.ObjectId `bson:"_id,omitempty"`
  Title       string
  Description string
  CreatedOn   time.Time
  Creator     string
  Visits      int
  Score       int
}

在我的controllers/crud.go中,我试图使用Horse结构体。

package controllers

import (
  "html/template"
  "log"
  "net/http"
  "horseapp/models"
)
[...]
var horseStore = make(map[string]Horse) //这里引发了未定义错误

但是当我运行go install horseapp时,我得到了undefined: Horse的错误。

这里有什么问题,如何修复?

英文:

Here is my noobish problem. I have this struct in my models/model.go

    package models
    
    import (
      "time"
      "gopkg.in/mgo.v2/bson"
    
    )
    
    type Horse struct {
    	Id    bson.ObjectId `bson:"_id,omitempty"`
    	Title       string
    	Description string
    	CreatedOn   time.Time
    	Creator		string
    	Visits	int
    	Score		int
    
    }

And in my controllers/crud.go I'm trying to use Horse struct

package controllers

import (
  "html/template"
  "log"
  "net/http"
  "horseapp/models"
)
[...]
var horseStore = make(map[string]Horse) //This raises undefined error

But I get undefined: Horse when I go install horseapp.

What is wrong here and how to fix it?

答案1

得分: 2

使用以下代码:

var horseStore = make(map[string]models.Horse)

当从另一个包中访问标识符时,你总是需要使用包名和一个点作为前缀:package.Identifier

英文:

Use

var horseStore = make(map[string]models.Horse)

When accessing an identifier from another package you will always have to prefix it with the packages name and a dot: package.Identifier

huangapple
  • 本文由 发表于 2016年2月22日 22:54:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/35556717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定