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?
As the compiler mentions, you can't extend existing types in another package.
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.
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.
The LinkedList
type is in the list
namespace, so change your usage of the type to:
type SomeType struct {
lst *list.LinkedList
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With