dongren9966 2015-08-12 13:44
浏览 45
已采纳

Golang:接口内的struct?

So I have an interface, called UserService inside a package service

I have two simple structs representing the body and response of a HTTP call. I have another struct implementing the UserService interface.

I want to put these structs, call them UserResponse and UserRequest inside the interface so other services can use them to make the HTTP call. Furthermore, the request and response should be available (struct UserReponse, not struct userResponse) so other parts of the code can use them.

I define a function in the interface called GetUser(request UserRequest) UserResponse

However, whenever I reference UserRequest I have to use service.UserRequest and not service.UserService.UserRequest. This is bad because I don't want user-related objects to go into the service namespace. I want each service related data to organized under its own interface, file, etc. Unfortunately, I get an error if I put UserResponse inside the UserService interface. So I put it at the same level as UserService, which is why they are showing up as service.UserResponse. How do I go about accessing UserResponse as service.UserService.UserResponse?

  • 写回答

2条回答 默认 最新

  • drzip28288 2015-08-12 14:22
    关注

    Here is a suggestion to organize your code in more "idiomatic" Go way:

    package user
    
    type Request struct {
        ...
    }
    
    type Response struct {
        ...
    }
    
    type Service interface {
       GetUser(r Request) Response
    }
    

    Outside of user package the code will look like:

    s := user.NewService()
    var req user.Request
    var resp user.Response
    resp = s.GetUser(req)
    

    As you can see the code uses much shorter names and still remains very readable.

    Package names like service shows that you organize the code in your app by layers instead of by features. I wouldn't recommend it. Here is interesting article about it: http://www.javapractices.com/topic/TopicAction.do?Id=205. It uses Java but the principle applies to any programming language.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?