方法接收者含糊不清 [英] Method receivers ambiguity

查看:102
本文介绍了方法接收者含糊不清的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天在旅途中工作。我注意到我可以将结构文字传递给与指向结构的指针相关的方法,反之亦然。为什么这是允许的?

 包主
$ b导入(
fmt


类型顶点结构{
X,Y float64
}

func(v Vertex)Scale(f float64){
vX = vX * f
vY = vY * f
}

func(v * Vertex)ScaleP(f float64){
vX = vX * f
vY = vY * f
}

func main(){
v:=& Vertex {3,4}
vLiteral:= Vertex {3 (5)
fmt.Println(v)

v.ScaleP(5)
fmt.Println(v) )

vLiteral.Scale(5)
fmt.Println(vLiteral)

vLiteral.ScaleP(5)
fmt.Println(vLiteral)

输出:

& {3 4} 
& {15 20}
{3 4}
{15 20}


解决方案

请参阅方法集


一个类型可能有一个与之关联的方法集(§Interfacetypes,§Methoddeclarations)。接口类型的方法集是它的接口。任何其他类型T的方法集由所有具有接收方类型T的方法组成。相应的指针类型* T的方法集是所有具有接收方* T或T的方法的集合(也包含方法集合T)。其他规则适用于包含匿名字段的结构,如结构类型部分所述。任何其他类型都有一个空方法集。在一个方法集合中,每个方法必须有唯一的方法名称。



类型的方法集合决定了类型实现的接口和可以使用的方法该类型的接收者。 b href =http://golang.org/ref/spec#Calls =noreferrer>电话:


如果(x的类型)的方法集包含m,并且参数列表可以分配给m的参数列表,则方法调用xm()是有效的。如果x是可寻址的,并且& x的方法集包含m,则x.m()是(& x).m()的简写:


Working on the go tour today. I noticed that I could pass struct literals to methods associated with pointer to structs, and vice versa. Why is this allowed?

package main

import (
    "fmt"
)

type Vertex struct {
    X, Y float64
}

func (v Vertex) Scale (f float64) {
    v.X = v.X * f
    v.Y = v.Y * f
}

func (v *Vertex) ScaleP(f float64) {
    v.X = v.X * f
    v.Y = v.Y * f
}

func main() {
    v := &Vertex{3, 4}
    vLiteral := Vertex{3, 4}

    v.Scale(5)
    fmt.Println(v)

    v.ScaleP(5)
    fmt.Println(v)

    vLiteral.Scale(5)
    fmt.Println(vLiteral)

    vLiteral.ScaleP(5)
    fmt.Println(vLiteral)
}

Output:

&{3 4}
&{15 20}
{3 4}
{15 20}

解决方案

See Method sets:

A type may have a method set associated with it (§Interface types, §Method declarations). The method set of an interface type is its interface. The method set of any other type T consists of all methods with receiver type T. The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T (that is, it also contains the method set of T). Further rules apply to structs containing anonymous fields, as described in the section on struct types. Any other type has an empty method set. In a method set, each method must have a unique method name.

The method set of a type determines the interfaces that the type implements and the methods that can be called using a receiver of that type.

EDIT:

See also 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():

这篇关于方法接收者含糊不清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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