英文:
Importing Packages
问题
我正在尝试学习Go,并编写一些测试程序,但在导入我的包时遇到了问题。我在Go Workspace的目录树中有以下结构(在src目录下)($GOPATH):
$GOPATH/src/gogoboy
│ main.go
│
├───cpu
│ flags.go
│ instructions.go
│ registers.go
│
└───memory
memories.go
如你所见,我目前有两个包:cpu和memory,这是我的main.go文件:
package main
import (
"gogoboy/cpu"
"gogoboy/memory"
)
func main() {
cpu.InitializeRegisters()
memory.WriteRAM(0x00, 0xFF)
}
问题是:cpu包和memory包位于同一级目录,cpu包可以正确导入并使用其中的每个函数,但是memory包会引发错误:
.\main.go:10: undefined: memory.WriteRAM
我真的不明白发生了什么,有人能给个解决方法吗?
文件memory/memories.go的内容如下:
package memory
const size uint16 = 0x2000
type Memories struct {
RAM [size]uint8
VRAM [size]uint8
}
func (memory *Memories) WriteRAM(position uint16, value uint8) {
memory.RAM[position] = value
}
英文:
I'm trying to learn Go and I'm writing some test programs, but I'm having a problem when importing my packages. I have this directory tree in my Go Workspace (inside src directory) ($GOPATH):
$GOPATH/src/gogoboy
│ main.go
│
├───cpu
│ flags.go
│ instructions.go
│ registers.go
│
└───memory
memories.go
As you can see I've 2 packages at this moment: cpu and memory and this is my main.go:
package main
import (
"gogoboy/cpu"
"gogoboy/memory"
)
func main() {
cpu.InitializeRegisters()
memory.WriteRAM(0x00, 0xFF)
}
The problem is: The package cpu, at the same level of package memory, is imported correctly and I can use every cpu function but, the package memory raises the error:
.\main.go:10: undefined: memory.WriteRAM
I really can't understand what's happening, can anyone give a way to solve?
File memory/memories.go
package memory
const size uint16 = 0x2000
type Memories struct {
RAM [size]uint8
VRAM [size]uint8
}
func (memory *Memories) WriteRAM(position uint16, value uint8) {
memory.RAM[position] = value
}
答案1
得分: 6
你没有做你认为你正在做的事情;看起来你想在一个内存结构体上调用一个方法,但是编译器正在寻找一个名为WriteRam的函数,因为你调用方法的方式。
看一下你在memory.go中的签名:
func (memory *Memories) WriteRAM(position uint16, value uint8)
你有一个接收器func (memory *Memories)
。这意味着为了调用这个方法,你需要在某个地方声明一个memory.Memories变量。
我认为你可能希望你的main函数看起来像这样:
package main
import (
"gogoboy/cpu"
"gogoboy/memory"
)
func main() {
cpu.InitializeRegisters()
mem := memory.Memories{}
mem.WriteRAM(0x00, 0xFF)
}
英文:
You're not doing what you think you're doing; it looks like you WANT to call a method on a memory struct, but the compiler is looking for a function named WriteRam within the memory package because of how you're calling that method.
Look at your signature in memory.go:
func (memory *Memories) WriteRAM(position uint16, value uint8)
You have a receiver func (memory *Memories)
. This means that in order to call this method, you need to have a memory.Memories variable declared somewhere.
I think you might want your main to look like this:
package main
import (
"gogoboy/cpu"
"gogoboy/memory"
)
func main() {
cpu.InitializeRegisters()
mem := memory.Memories{}
mem.WriteRAM(0x00, 0xFF)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论