douzhang3356 2018-03-28 01:49
浏览 47

golang新建一个结构,但返回一个接口

Here are golang code, the func newXXX return an interface, but why it does not return a struct

type _ABitOfEverythingServer struct {
    v map[string]*examples.ABitOfEverything
    m sync.Mutex
}

type ABitOfEverythingServer interface {
    examples.ABitOfEverythingServiceServer  // interface
    examples.StreamServiceServer            // interface
}

func newABitOfEverythingServer() ABitOfEverythingServer { 
//<-why not return _ABitOfEverythingServer, is it a good way?
    return &_ABitOfEverythingServer{
        v: make(map[string]*examples.ABitOfEverything),
    }
}
  • 写回答

2条回答 默认 最新

  • doucheng1884 2018-03-28 03:30
    关注

    First, you need to learn the basics of Go. Take A Tour of Go.

    Simplifying a complicated example,

    package main
    
    import "fmt"
    
    type S struct{ F int }
    
    type I interface{}
    
    func newI() I {
        return &S{F: 42}
    }
    
    func main() {
        i := newI()
        s := i.(*S)
        f := s.F
        fmt.Println(f)
    }
    

    Playground: https://play.golang.org/p/tHbTZHEQZ-L

    Output:

    42
    

    The newI function returns a value of interface type I, which contains a value of concrete type *S.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分