如何在同一个包中的一个类中使用另一个类?

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

How to use one class in another class that is in the same package?

问题

我对Go语言还比较新,正在制作一个小型的单词卡片应用程序。
我的包结构如下:

  1. VocabHelper
  2. |
  3. -|src
  4. --|com
  5. ---|wks
  6. ----|card
  7. ------Card.go
  8. ------Deck.go
  9. ----|main
  10. ------main.go

Deck和Card是两个独立的类,但它们在同一个包中:

Card.go

  1. package card
  2. type Card struct{
  3. Question string
  4. Answer string
  5. }

Deck.go

  1. package card
  2. import (
  3. "math/rand"
  4. )
  5. type Deck struct{
  6. Cards []card.Card
  7. }

当我尝试编译项目时,编译器报错说undefined:card,尽管card和deck在同一个包中。我该如何在deck类中使用card类?

英文:

I'm fairly new to Go and I'm making an a small flashcards app.
My package structure is this

  1. VocabHelper
  2. |
  3. -|src
  4. --|com
  5. ---|wks
  6. ----|card
  7. ------Card.go
  8. ------Deck.go
  9. ----|main
  10. ------main.go

Deck and Card are two separate classes but they're in the same package:

Card.go

  1. package card
  2. type Card struct{
  3. Question string
  4. Answer string
  5. }

Deck.go

  1. package card
  2. import (
  3. "math/rand"
  4. )
  5. type Deck struct{
  6. Cards []card.Card
  7. }

When I try to compile the project, the compiler says undefined:card even though card is in the same package as deck. How can I use the card class in the deck class?

答案1

得分: 5

去掉card.部分,它应该可以工作。它们都在同一个包中。

  1. type Deck struct{
  2. Cards []Card
  3. }
英文:

Leave off the card. part, and it should work. They're both in the same package.

  1. type Deck struct{
  2. Cards []Card
  3. }

huangapple
  • 本文由 发表于 2013年12月28日 05:20:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/20807989.html
匿名

发表评论

匿名网友

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

确定