douhuang4166 2014-01-10 22:26
浏览 19
已采纳

方法接收者是否作为指针之间的区别

Why don't I have to define PrintValue() as a pointer receiver (*One) to be able to print "hello"?

package main
import "fmt"


type One struct{
    a string
}
func (o *One)AssignValue(){
    o.a = "hello"
}
func (o One)PrintValue(){
    fmt.Println(o.a)
}

func main() {
    one := One{}
    one.AssignValue()
    one.PrintValue()
}
  • 写回答

1条回答 默认 最新

  • dtyqflrr775518 2014-01-10 22:29
    关注

    Because one is already of type One. The instantiation syntax

    t := One{}
    

    creates a value of type One while the form

    p := &One{}
    

    creates a pointer to a value of type One.

    This means that nothing is to be done when calling t.PrintValue as the receiver type (One) is already the same as the type of t (One as well).

    When calling p.PrintValue the compiler automatically converts an addressable variable to its pointer form because the receiver type (One) is not equal to the type of p (*One). So the expression

    p.PrintValue()
    

    is converted to

    (*p).PrintValue()
    

    There is also a conversion necessary when calling t.AssignValue as this method has a pointer receiver but we're supplying a value. This is also done automatically by the compiler where possible.

    From the spec on calls:

    A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m()

    This means the expression

    t.AssignValue()
    

    is converted to

    (&t).AssignValue()
    

    Note that this is not always possible. For example when returning a value from a function:

    func NewOne(s string) One { return One{s} }
    
    NewOne("foo").AssignValue() // Not possible
    
    x := NewOne("foo")
    x.AssignValue() // Possible, automatically converted
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真