gpt4 book ai didi

pointers - GO - 隐式方法如何工作?

转载 作者:IT王子 更新时间:2023-10-29 02:27:35 24 4
gpt4 key购买 nike

In GO, I learnt that,

1)

Programmer can only define methods on named types(X) or pointer(*X) to named types

2)

An explicit method definition for type X implicitly defines the same method for type *X and vice versa, so, my understanding is, If I declare,

func (c Cat) foo(){
//do stuff_
}

and declare,

func (c *Cat) foo(){
// do stuff_
}

then GO compiler gives,

Compile error: method re-declared

which indicates that, pointer method is implicitly defined and vice versa


With the given named type(Cat),

type Cat struct{
Name string
Age int
Children []Cat
Mother *Cat
}

Scenario 1

Method(foo) defined on a named type(Cat), by programmer,

func (c Cat) foo(){
// do stuff....
}

that implicitly defines method(foo) on pointer(*Cat) to named type, by GO compiler, that looks like,

func (c *Cat) foo(){
// do stuff....
}

On creating variables of named type(Cat)

var c Cat
var p *Cat = &c

c.foo() has the method defined by programmer.

Question 1:

On invoking p.foo(), does implicit pointer method receive the pointer(p)?


Scenario 2

Method(foo) defined on a pointer(*Cat) to named type, by the programmer,

func (c *Cat) foo(){
// do stuff....
}

that implicitly defines method(foo) on named type(Cat), by the GO compiler, that looks like,

func (c Cat) foo(){
// do stuff....
}

On creating variables of named type(Cat)

var c Cat
var p *Cat = &c

p.foo() has method defined by programmer(above).

Question 2:

On invoking c.foo(), does the implicit non-pointer method receive the value c?

最佳答案

  1. 类型 X 的显式方法定义隐式定义类型 *X 的相同方法,反之亦然。

这是不正确的。方法不是隐式定义的。编译器为您做的唯一一件事就是将 c.foo() 隐式替换为 (*c).foo()c.foo()(&c).foo() 为了方便。查看tour of Go

  1. 根据您的显式声明,方法的接收者是 T 类型或 *T 类型。

关于pointers - GO - 隐式方法如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com