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 爬虫爬取网站的一些信息
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错