Colleen Larsen
Colleen Larsen

Reputation: 733

How to import structs from another package in Go

I am trying to import the following struct into a separate package in Golang

package models
type Category struct {
    Title string
    Description string
    Parent *Category
    ParentId int
}

into package controllers as follows

import(
"website.com/Owner/blog/app/models"
)
func (c Category) Update(){
   //do something here
}

However, I get the error unresolved type Category How should I go about importing a struct into a separate package with Go?

Upvotes: 1

Views: 11689

Answers (1)

val
val

Reputation: 8689

You need to fully qualify your names: don't use Category, but use models.Category. The doc there should get you started. You can do:

import "fmt"

func main() {
    fmt.Println("Hello")
}

Or:

import f "fmt"

func main() {
    f.Println("Hello")
}

Or ditch the qualification entirely (however, this is considered poor style: being able to see, at a glance, where some structure or function comes from is very handy when looking at code):

import . "fmt"

func main() {
    // Where does that come from ? Hard to know without 
    // intimate knowledge of the package
    Println("Hello")
}

One last thing you can do is to 'typedef' your remote structure for easier use locally:

import "website.com/Owner/blog/app/models"

type Category models.Category

Note however that it create a new type, although with the same underlying type.

Upvotes: 4

Related Questions