gpt4 book ai didi

go - 从包的子目录引用包中的接口(interface)

转载 作者:数据小太阳 更新时间:2023-10-29 03:29:15 26 4
gpt4 key购买 nike

有一个带有子目录(子包)的包,并且不能使用子包中包中定义的接口(interface)。

所以,

有包f1 创建子目录 f2

在f1中定义一个接口(interface):

---/f1/file1.go ---

package f1

type Miner interface {
Foo()
}

func TheFunction( m Miner) { /* blah */ }

在 f2 中创建一个结构,它应该是 f1 中接口(interface)的一部分:

---/f1/f2/file2.go ---

package f2

type Mine struct {
i int
}
func (m *Mine) Foo() {/* blah */}

在另一个文件中,我尝试使用该包并创建 Mine 结构并将其作为接口(interface) Miner 传递给一个函数:

--- ./test_file.go ---

package main

import (
"f1"
"f1/f2"
)

m := f2.Mine{}
f1.TheFunction(&m)

这给出了一个错误“f2.Mine 没有实现接口(interface) f1.Miner...想要 f1.Foo() 但有 f2.Foo()

希望这是有道理的。 那么,如何在使用 f1 接口(interface)的子目录 f2 中创建结构?

谢谢,

最佳答案

您的包或目录绝对没有问题:您的f2.Mine 只是没有实现Miner。只有 f2.*Mine 有方法 Foo()

看看http://golang.org/doc/faq#methods_on_values_or_pointershttp://golang.org/ref/spec#Method_sets

关于go - 从包的子目录引用包中的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23257021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com