duandao8607 2019-07-12 03:40
浏览 143

Golang指针接收器技术混乱

I recently started to learn Golang for a work project. I come from a 'c' background and have some confusion about the technicalities of Pointer Receivers in functions. Am I to assume receiver are generalized and don't care if the object is actually a pointer or a literal, it will translate it to whatever the receiver type is.

I know my question wording may be confusing so here is some code for example:

func (v *clients) makePtr() {
    (*v).slice = make([]client, 0)
    return
}

func (v clients) makeLit() []client {
    return make([]client, 0)
}

func main() {
    clsPtr := &clients{} // pointer
    clsLit := clients{}  // literal

    clsLit.makePtr() // literal with pointer reciever
    clsLit.makeLit() // literal with pointer reciever
    clsPtr.makePtr() // pointer with literal reciever
    clsPtr.makeLit() // pointer with pointer reciever
}

I expected the the functions with pointer receivers to only work on pointers and vice versa. from this am I just suppose to assume receivers are a blanket statement and don't care if its a pointer, literal?

EDIT: Apologizes guys, I may not have been to clear with my question, I understand that a pointer receiver is used to modify a object but I'm more confused as to the syntax, why does a pointer receiver work for both a literal and a pointer, since it receives a pointer shouldn't it only work on a pointer?

  • 写回答

2条回答 默认 最新

  • dongqiu9018 2019-07-12 04:35
    关注

    In golang these are called methods which are function with receiver. The receiver argument can be passed by value or by pointer.

    You can write functions like below which are plain functions.

     type Client struct{}
    
    //A pointer to Client    
    func makePtr(c *Client){
        //do something with c
    }
    
    //A copy of client is made.
    func makeLit(cs Client){
        //do something with c
    }
    

    Instead if you write methods then it gives association with struct.

    type Client struct{}
    
    func (c *Client) makePtr(){
        //do something with c
    }
    
    //A copy of client is made.
    func (c Client)makeLit(){
        //do something with c
    }
    

    The main purpose of methods I see in golang is for interface implementation It is by virtue of methods structs implement (or satisfy) interfaces.

    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图