Reputation: 15034
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
?
Upvotes: 1
Views: 3121
Reputation: 9569
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.
Upvotes: 5
Reputation: 879
Go is not Java; Go is even not C++. You should think of Go as "C with interfaces".
In particular, you cannot do as you want, as you cannot nest struct definitions in interface definitions. Note that you can nest structs inside structs, but you cannot instantiate a nested struct directly.
The closest you can do is to move each logical group of objects to its own package.
Upvotes: -1