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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?