如何共享嵌入的结构体指针

huangapple go评论97阅读模式
英文:

How to share embedded struct pointer

问题

我有以下代码:

一个名为controller的结构体,其中包含匿名字段。

type controller struct {
    *base.Controller
    store *data
}

如你所见,*base.Controller 是一个匿名字段指针。然后有一个第二个结构体,也由 *base.Controller 组成。

type expiredError struct {
    *base.Controller
    local string
}

我按照以下方式初始化了controller结构体:

c := &controller{base.New(rw, r, false, "controller/account"), nil}
c.Title = "Activate account"
c.serve()

controller上的base.Controller 是通过base.New() 函数进行初始化的。

现在我有一个controller方法,它初始化了expiredError结构体,并且它应该共享base.Controller的指针给expiredError的base.Controller。

func (rcv *controller) validate() error {

    ....

    // 如果激活帐户的时间已过期
    if time.Now().Unix() > rcv.store.Expired {
        // 从neo4j中删除已注册的用户
        maccount.Delete(rcv.store.Email, rcv.Local)

        return &expiredError{base.Controller, rcv.Local}
    }

    return nil
}

我在这里遇到了一个编译错误:

type base.Controller is not an expression

英文:

I have following code:

A struct controller, that have anonymous fields.

type controller struct {
	*base.Controller
	store *data
}

As you can see, *base.Controller is anonymous fields pointer.
Then a second struct that composed with *base.Controller too.

type expiredError struct {
	*base.Controller
	local string
}

I initialized the controller struct as follow:

c := &controller{base.New(rw, r, false, "controller/account"), nil}
c.Title = "Activate account"
c.serve()

The base.Controller on controller is initialize with base.New() function.

Now I have on controller methods, that initialize the expiredError struct and it should share the pointer of base.Controller to base.Controller of expiredError too.

func (rcv *controller) validate() error {

	....

	// If time for activating account is expired
	if time.Now().Unix() > rcv.store.Expired {
		// Delete registered user from neo4j
		maccount.Delete(rcv.store.Email, rcv.Local)

        return &expiredError{base.Controller, rcv.Local}
	}

	return nil
}

I've got here a compiler error

type base.Controller is not an expression

答案1

得分: 3

你可以通过提及父类的实例来引用匿名字段:

rcv.Controller

(因为匿名字段的“名称”与字段的类型相同)

在以下类似的示例中可以看到:

英文:

You can try referencing the anonymous field by mentioning the instance of the parent class:

rcv.Controller

(since the "name" of an anonymous field is the same as the type of the field)

See a similar example in:

huangapple
  • 本文由 发表于 2015年1月3日 05:22:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/27748718.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定