登录
首页 >  Golang >  Go问答

允许接口方法接受/返回具有相同结构的结构体吗?

来源:stackoverflow

时间:2024-02-13 08:06:22 432浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《允许接口方法接受/返回具有相同结构的结构体吗?》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我想创建一个库,导出一个函数来定义自己的依赖项,而不使用外部包(不包括 std lib)中的类型。

问题是,如果我的依赖项是 interface 类型,且其方法返回 struct,则使用者必须使用 interface 中声明的确切结构。

在我有两个或多个库的情况下,每个库共享相同的 interface 签名,但每个包定义自己的 interface (接口隔离),当涉及返回 struct 类型的方法时,它们会发生冲突。

package mylibrary

type result struct {
  value string
}

type ifoo interface {
  foo() result
}

func dofoo(f ifoo) {
  f.foo()
}

使用上述代码,任何实现此库的人都必须完全使用 mylibrary.result 结构来满足 ifoo 接口。

如果我有多个包定义它们自己的依赖项的接口,这可能会变得困难或不可能

请参阅以下示例:https://replit.com/@davidalsh/usedcarefreebrain#main.go

// main.go
// creating an object that satisfies the contract roughly

import (
    packagea "main/package-a"
    packageb "main/package-b"
)

type result struct {
    message string
}

type foo struct {}

// even though result is the same shape, this needs to
// return either packagea.result or packageb.result
func (*foo) foo() result {
    return result{}
}

func main() {
    dep := foo{}
    packagea.dofoo(dep) // foo does not implement packagea.ifoo
    packageb.dofoo(dep) // foo does not implement packageb.ifoo
}

这似乎是一个奇怪的限制。接口上的方法可以返回 stringint[]int 等类型,但不能返回 struct

我是否应该返回一个带有来自 ifoo.foo 的 getter/setter 的接口?

type iresult interface {
  message() string
}

type ifoo interface {
  foo() iresult
}

如果我想使用 struct 作为函数的参数怎么办?我是否也应该只接受吸气剂接口?

interface IUserDetails {
  FirstName() string
  LastName() string
  Age() int
}

func SayHello(user IUserDetails) {
  fmt.Println("Hello", user.FirstName())
}

或者有更好的方法吗?


正确答案


在第三个包中定义类型:

common/common.go

package common

type result struct {
    message string
}

在所有其他包中使用此包:

ma​​in.go

package main
import (
    "main/common"
    packagea "main/package-a"
    packageb "main/package-b"
)

type foo struct{}

func (*foo) foo() common.result {
    return common.result{}
}

func main() {
    dep := &foo{}
    packagea.dofoo(dep)
    packageb.dofoo(dep)
}

package-a/packagea.go

package packagea

import "main/common"

type IFoo interface {
    Foo() common.Result
}

func DoFoo(f IFoo) {
    f.Foo()
}

Run the program on the Go Lang Playground

到这里,我们也就讲完了《允许接口方法接受/返回具有相同结构的结构体吗?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>