dream12001 2014-09-05 10:22
浏览 23
已采纳

匿名字段作为指针或嵌入

What is the different between anonymous field as pointer or anonymous field as usual. Consider, how I embed Foo into Bar struct.

Look at the following code snippet:

First with anonymous field as pointer

package main

import (
    "fmt"
)

type Foo struct{}

func (*Foo) Run() {
    fmt.Println("Hello")
}

type Bar struct {
    *Foo
}

func main() {
    bar := new(Bar)
    bar.Run() 
}

and second anonymous field as usual:

package main

import (
    "fmt"
)

type Foo struct{}

func (*Foo) Run() {
    fmt.Println("Hello")
}

type Bar struct {
    Foo
}

func main() {
    bar := new(Bar)
    bar.Run()
}

What is different between them?

Update: I pick up this sample from revel webframework, how they extend a custom controller. Look at this code snippet

type App struct {
    *revel.Controller
}

why do revel use pointer to embed controller struct. What is the sense of it?

  • 写回答

2条回答 默认 最新

  • doulu1325 2014-09-05 10:46
    关注

    Given that Foo is an empty struct, embedding it in Bar will make no change to to the memory footprint of Bar.

    However, embedding a pointer to Foo will change Bar; it will add a pointer value, initialized to nil. If the only purpose of Foo is to have methods, then using a pointer is superfluous.

    Of course, were you to add some fields into Foo, then, in the pointer case, you'd also need to add bar.Foo = new(Foo) into main, or else you'll have problems.

    The advantage of using a pointer would be that you could share the same Foo instance between multiple instances of Bar, or else you could keep it nil until you really need it.

    The disadvantage would be that it would be slightly more trouble, and slightly less efficient, if there's always a 1-to-1 Foo-to-Bar mapping.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口