什么时候是一个指针习惯? [英] When is a pointer idiomatic?

查看:133
本文介绍了什么时候是一个指针习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自没有显式指针的语言,所以我不太了解它们存在的意义(没有双关语意思)。



问题是我不知道,大多数时候,我为什么传递一个指针函数。我明白,当你传递一个指针时,对变量的修改会在任何地方完成,但是有什么意义呢?为什么不只是修改值并返回结果?



例如, http.HandlerFunc 是一个接收 http.ResponseWriter * http.Request 作为参数。我已经读过界面实际上是指针(是吗?),但我没有得到的是,为什么?

为什么我得到一个指向作家?我没有修改它,我只是写信给它。而且,为什么我得到一个指向请求的指针?我正在做的东西像 request.FormValue()



我想通过这些来确定例子,这个问题的答案是我什么时候需要传入一个指针?。

我现在正在编写代码,尝试编译它,通过添加一个&符号和星号来修正我必须传入指针的错误,直到错误通过。不过,我觉得这种半知半懂的指针概念很快就会在我的背后咬我一口。

可以将指针看作指向对象内存地址的值。与大多数数据结构相比,指针很小(比如说8字节)。

很多时候你会得到一个指向对象的指针,因为通过这些指针要快得多字节,而不是创建要传递的整个对象的副本。

对于Request对象,创建请求下的所有内容(payload,headers和whatnot)相比,只需传递一个可访问原始数据的指针。


I come from languages which don't have explicit pointers, so I don't really understand the point of their existence (no pun intended).

The problem is that I have no idea, most of the time, why I am passing a pointer to a function. I do understand that when you pass in a pointer, modifications to the variable are done to the value everywhere, but what's the point? Why not just modify the value and return the result?

For example, http.HandlerFunc is a function that receives http.ResponseWriter and *http.Request as arguments. I have read that interfaces are in fact pointers (is that right?), but what I'm not getting is, why?

Why am I getting a pointer to a writer? I'm not modifying it, I'm merely writing to it. And, why am I getting a pointer to a request? I am doing stuff like request.FormValue().

What I'm trying to determine here, through these examples, is the answer to the question, "when do I need to pass in a pointer?"

The way I do it right now is to write my code, try to compile it, fix the errors that say I must pass in a pointer by adding an ampersand and asterisk, until the errors pass. However, I feel this half-understood concept of pointers is going to bite me in the backside some day very soon.

解决方案

You can think of a pointer as a value that points to the memory address of an object. Pointers are small (say 8 bytes) compared to most data structures.

A lot of times you will get a pointer to an object because it is much faster to pass those 8 bytes than to create a copy of the entire object that you want to pass.

In the case of a Request object it would be very expensive to create a copy of everything under the request (the payload, headers, and whatnot) compared to just passing a pointer that has access to the original data.

这篇关于什么时候是一个指针习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆