dongqie4402 2016-01-25 19:02
浏览 40
已采纳

指针什么时候惯用的?

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.

  • 写回答

3条回答 默认 最新

  • doukao2180 2016-01-25 19:13
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输