登录
首页 >  Golang >  Go问答

接口嵌入:未实现结构的方法

来源:stackoverflow

时间:2024-03-03 18:57:25 293浏览 收藏

大家好,今天本人给大家带来文章《接口嵌入:未实现结构的方法》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我不明白为什么接口组合在实现中满足要求时不“继承”父接口的方法。

package main

import (
    "fmt"
)

type testrepository interface {
    findbyid(int) (error)
}

type testservice interface {
    testrepository
    method(id int) error
}



type testservice struct {
    implrepository testrepository
}

func newtestservice(r testrepository) testservice {
    return &testservice{implrepository: r}
}

编译此代码时,我得到: *testservice 未实现 testservice(缺少 findbyid 方法),而我实际上希望它实现它,因为“implrepository”的类型是 testrepository。

如果我这样做,它就会起作用:

func NewTestService(r TestRepository) *testService {
    return &testService{implRepository: r}
}

但这有点违背了界面的目的(至少就服务而言)

我缺少什么/应该如何完成?


解决方案


您的问题的答案很简单:“您没有按照您需要的方式构建界面。”您已将 testrepository 设为结构成员 - 这不会“继承”该接口上的方法。您需要的是以下内容:

type testService struct {
    TestRepository
}

func NewTestService(r TestRepository) TestService {
    return &testService{TestRepository: r}
}

当然,struct testservice 仍然需要实现 method(id int) error 才能实际工作。

到这里,我们也就讲完了《接口嵌入:未实现结构的方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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