如何导入一个位于其他包内的结构体?

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

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

问题

你好!要在其他包中使用已定义的结构体,你需要确保以下几点:

  1. 确保你在导入包时使用了正确的路径。在你的示例中,你导入了一个名为"list"的包,但是没有提供完整的包路径。请确保你提供了正确的包路径,例如:"github.com/your-username/your-package/list"。

  2. 确保你在导入包时使用了正确的包名。在你的示例中,你导入了一个名为"list"的包,但是在包中定义的结构体名为"LinkedList"。请确保你使用了正确的包名,例如:"github.com/your-username/your-package/list"。

  3. 确保你在导入包后正确使用了结构体。在你的示例中,你尝试在"main.go"文件中使用"LinkedList"结构体,但是你需要在导入包后使用完整的包名来引用结构体,例如:"list.LinkedList"。

请检查以上几点,看看是否能解决你的问题。如果问题仍然存在,请提供更多的代码和错误信息,以便我能够更好地帮助你。

英文:

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?

答案1

得分: 24

LinkedList 类型位于 list 命名空间中,因此请将您对该类型的使用更改为:

type SomeType struct {
    lst *list.LinkedList
}
英文:

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

type SomeType struct {
    lst *list.LinkedList
}

huangapple
  • 本文由 发表于 2014年1月18日 09:16:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/21198858.html
匿名

发表评论

匿名网友

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

确定