嵌入的方法可以访问“父”字段? [英] Can embedded methods access "parent" fields?

查看:74
本文介绍了嵌入的方法可以访问“父”字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了大量的规格阅读和代码测试,我认为答案是否定的,但我想要以确保我没有遗漏任何东西。



目标

基本上,我试图为Go创建一个Active Record样式的ORM,因为我喜欢它的可读性以及它从后端数据存储中抽象出来的方式。通过嵌入常见的CRUD方法,我宁愿写 user.Save() data.Save(用户)用户结构。

示例

 软件包主要

导入(
fmt
反映


func main(){
test: = Foo {Bar:& Bar {},Name:name}
test.Test()
}

type Foo struct {
* Bar
名称字符串
}

func(s * Foo)方法(){
fmt.Println(Foo.Method())
}

类型结构{
}

func(s * Bar)Test(){
t:= reflect.TypeOf(s)
v := reflect.ValueOf(s)
fmt.Printf(model:%+ v%+ v%+ v \ n,s,t,v)
fmt.Println(s.Name )
s.Method()
}

http://play.golang.org/p/cWyqqVSKGH



问题



有没有办法让mak (例如: s.Name s)可以访问顶层字段(不知道Go中的正确术语是什么)。方法()



感谢您将时间捐献给新的Gopher。

Test 方法的接收者是 Bar 指针,并且无法判断它是否嵌入。



如果你真的想走这条路,一个选择是将一个接口{} 成员添加到 Bar 中,并要求将其设置为包含的类型类型。初始化这个成员可能是谁创造价值的责任,或者可能需要调用者将值传递给一些ORM方法来设置它。这不是特别漂亮,但它可能是你可以做的最好的。



因为这样做,将API的结构设计为 db.Save(user)而不是 user.Save()?前者提供了扩展到多个数据库的明显方式,而后者似乎更可能依赖于全局状态。


Background

I've done a fair amount of spec reading and code testing and I think the answer is no, but I want to make sure I'm not missing anything.

Goal

Basically, I'm trying to create a Active Record style ORM for Go, because I like how readable it is and how abstracted it is from its back end data store. I'd rather write user.Save() than data.Save(user) by embedding common CRUD methods on the user struct.

Example

package main

import (
    "fmt"
    "reflect"
)

func main() {
    test := Foo{Bar: &Bar{}, Name: "name"}
    test.Test()
}

type Foo struct {
    *Bar
    Name string
}

func (s *Foo) Method() {
    fmt.Println("Foo.Method()")
}

type Bar struct {
}

func (s *Bar) Test() {
    t := reflect.TypeOf(s)
    v := reflect.ValueOf(s)
    fmt.Printf("model: %+v %+v %+v\n", s, t, v)
    fmt.Println(s.Name)
    s.Method()
}

http://play.golang.org/p/cWyqqVSKGH

Question

Is there a way to make top-level fields (not sure what the correct term in Go is for these) accessible from embedded methods (eg: s.Name or s.Method()?

Thank you donating your time to a new Gopher.

解决方案

Go doesn't provide any support for what you're after: the receiver of your Test method is a Bar pointer, and there is no way to tell whether it is embedded or not.

If you really want to go this route, one option would be to add an interface{} member to Bar and require that types that it be set to the containing type. Initialising this member could either be the responsibility of whoever created the value, or perhaps require callers to pass the value to some ORM method to set it. This isn't particularly pretty, but it's probably the best you can do.

With that out of the way, is it really that bad to structure the API as db.Save(user) rather than user.Save()? The former offers an obvious way to extend to multiple databases, while the latter seems more likely to rely on global state.

这篇关于嵌入的方法可以访问“父”字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆