英文:
Replicate http.HandleFunc()'s "coding style" to create our own methods/functions
问题
以下是翻译好的内容:
有一个已回答的问题可以帮助你理解我想要表达的内容。
Go语言中有许多内置函数,其中函数参数以这种方式分配。我想在我的日常编码中使用这种编码风格。
我想编写一个类似的函数/方法,它将从某个地方获取其参数值,就像http.Handlefunc
的w
和r
一样。
func (s SchoolStruct) GetSchoolDetails(name string){
// 这里的参数"name"应该像http.HandleFunc()的"w"和"r"一样被分配。
}
英文:
There is an answered question which will help you understand what exactly I want to say.
There are many built-in Go functions where the function parameters get assigned this way. I want to use that coding style in my daily coding life.
I want to write a similar function/method which will get its parameter values from somewhere just like http.Handlefunc
's w
and r
.
func (s SchoolStruct) GetSchoolDetails(name string){
// here the parameter "name" should get assigned exactly like http.HandleFunc()'s "w" and "r".
}
答案1
得分: 2
http的作用是注册一个回调函数,并在需要时使用它。你不需要传递它所需的参数,因为服务器的实现会提供这些参数,并保持正确的状态。如果你想采用这种方法,首先你需要问自己:
是否存在一种通用的抽象方法来计算这些参数?我编写的函数只是对某些事件做出反应吗?这个函数是否有任何副作用?它是否将返回值返回给系统?
当你修改现有系统并使用独立单元扩展其行为时,这种方法非常有效。换句话说,它可以与强大的API集成。
你可能正确,这是一种做事情的方式,但并不适用于所有情况。它只适用于特定类型的任务。
正如@mkopriva指出的,声明规则和要满足的要求是在Go中执行这种风格的已知方法。你必须意识到,你通过函数指针或接口封装的逻辑必须由你间接调用的其他代码传递和控制。
当系统的所有组件都在你的控制下,并且系统只有一个逻辑需要运行时,我无法想象为什么要这样做。
英文:
What http does is that it registers a callback and uses it when the time comes. You don't have to pass the arguments it takes, as servers implementation provides these arguments with correct state. If you want to copy this approach, first you have to ask:
Is there some kind of generic abstraction that computes these parameters? Is the function I write just reacting to something? Does this function have any side effects? Does it return value back to the system?
This approach is very good when you are modifying existing system, extending its behavior with independent units. So to speak, integrating into robust API.
You may be correct that this is a style of doing things, but you cannot use this style on everything. Its just too specific and good at certain group of tasks.
As @mkopriva pointed out, declaring rules and requirements, your logic should satisfy, is known way to execute this style in Go. You have to realize that your logic, encapsulated behind function pointer or interface, has to be passed and controlled by some other code you call indirectly.
I cannot possibly imagine going to such lengths when all components of the system are under your control and system has only one logic to run.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论