Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a struct that is inside of other package?

Tags:

struct

go

I tried to learn Go but I frequently feel frustrating because some basic features that other languages has seems not working in Go. So basically, I would like to use struct type that is define in other file. I was able to use functions except struct type. In main.go,

  package main

  import (
      "list"
  )

  func main() {
      lst := list.NewList(false)         
      lst.Insert(5)
      lst.Insert(7)
      lst.InsertAt(2, 1)
      lst.PrintList()
  }

This works perfectly (and all other functions) as I expect (list is in $GOPATH). In package list, I defined struct as follow:

type LinkedList struct {
    head    *node
    size    int
    isFixed bool
}

I wanted to use this struct in other struct, so I attempted to do something like this,

type SomeType struct {
    lst *LinkedList
}

But unfortunately, I got error that the type LinkedList is not defined. How can I use a struct that is defined in other package?

like image 573
REALFREE Avatar asked Jan 18 '14 01:01

REALFREE


People also ask

Is it possible in go to add a method to a struct from another package?

As the compiler mentions, you can't extend existing types in another package.

How do you access a struct from an external package in go?

Create a file father.go inside the father folder. The file inside the father folder should start with the line package father as it belongs to the father package. The init function can be used to perform initialization works and can also be used to confirm the correctness of the program before the execution begins.

Can't define receiver from another package in go?

You can only define methods on a type defined in that same package. Your DB type, in this case, is defined within your dbconfig package, so your entity package can't define methods on it. In this case, your options are to make GetContracts a function instead of a method and hand it the *dbconfig.


1 Answers

The LinkedList type is in the list namespace, so change your usage of the type to:

type SomeType struct {
    lst *list.LinkedList
}
like image 196
tlehman Avatar answered Oct 14 '22 21:10

tlehman