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 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)