如果我有这样的包范围变量:
var (
bus *Bus // THIS VARIABLE
)
// Bus represents a repository bus. This contains all of the repositories.
type Bus struct {
UserRepository *UserRepository
// ...
}
Run Code Online (Sandbox Code Playgroud)
...我可以访问bus我的存储库中的变量,以便它们可以相互访问,如果它们可以同时使用,我是否需要使用任何类型的互斥?
会发生什么的快速伪代码:
// Router
router.GET("/user/:id", c.FindUser)
// Controller
func (c *UserController) FindUser(w http.ResponesWriter, r *http.Request) {
w.Write([]byte(c.UserService.FindUser(r.Get("id"))))
}
// Service
func (s UserService) FindUser(id int) *domain.User {
return s.UserRepository.FindByID(id)
}
// Repository
func (r UserRepository) FindByID(id int) *domain.User {
// This is where the package-scope `bus` variable will be used
}
Run Code Online (Sandbox Code Playgroud)
在FindByID函数中,我可以使用package-scoped bus变量,当然可以同时访问它,因为只要HTTP请求触发它就会被调用,并且这些变量都是并发处理的.
| 归档时间: |
|
| 查看次数: |
352 次 |
| 最近记录: |