duandang2123 2013-12-03 18:25
浏览 47
已采纳

如果S包含匿名字段T,则S的方法集是否包括接收者* T的提升方法?

The title of the question is almost quoted from the golang specification:

Given a struct type S and a type named T, promoted methods are included in the method set of the struct as follows:

  • If S contains an anonymous field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.

This is a go playground shows that The method inc() is promoted.

package main

import (
    "fmt"
)

// just an int wrapper
type integer struct {
    i int
}

func (self *integer) inc() {
    self.i++
}

type counter struct {
    integer
}

func main() {
    c := counter{}

    c.inc()
    fmt.Println(c)
}
  • 写回答

1条回答 默认 最新

  • dopuzf0898 2013-12-03 19:05
    关注

    No the methods of *T would not be promoted. The specification doesn't explicitly allow it so it isn't allowed. However, there is a reason behind this.

    At times you may call a *T method on T. However, there is an implicit reference taken. Methods of *T are not considered part of T's method set.

    From the calls section of the Go specification:

    If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m()

    From the address operator section of the Go specification:

    For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal.

    If a S contains a *T, you don't even need to take its address so the methods can be called. If *S contains a T, you know T is addressable because T is a field selector of a pointer indirected struct. For S containing T, this cannot be guaranteed.


    UPDATE: why does that code work?

    Remember that *S contains the method set of *T. Also, as I quoted before:

    If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m()

    Put the two together and you have your answer. Counter is addressable and &counter contains the method set of *T. Therefore, counter.Inc() is shorthand for (&counter).Inc().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度