嵌入的方法可以访问“父”字段? [英] Can embedded methods access "parent" fields?
问题描述
目标 基本上,我试图为Go创建一个Active Record样式的ORM,因为我喜欢它的可读性以及它从后端数据存储中抽象出来的方式。通过嵌入常见的CRUD方法,我宁愿写 示例 http://play.golang.org/p/cWyqqVSKGH 问题 有没有办法让mak (例如: 感谢您将时间捐献给新的Gopher。 如果你真的想走这条路,一个选择是将一个 因为这样做,将API的结构设计为 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 Example 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: Thank you donating your time to a new Gopher. Go doesn't provide any support for what you're after: the receiver of your If you really want to go this route, one option would be to add an With that out of the way, is it really that bad to structure the API as 这篇关于嵌入的方法可以访问“父”字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
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()
}
s.Name
或 s)可以访问顶层字段(不知道Go中的正确术语是什么)。方法()
?
Bar
指针,并且无法判断它是否嵌入。
接口{}
成员添加到 Bar
中,并要求将其设置为包含的类型类型。初始化这个成员可能是谁创造价值的责任,或者可能需要调用者将值传递给一些ORM方法来设置它。这不是特别漂亮,但它可能是你可以做的最好的。
db.Save(user)
而不是 user.Save()
?前者提供了扩展到多个数据库的明显方式,而后者似乎更可能依赖于全局状态。user.Save()
than data.Save(user)
by embedding common CRUD methods on the user struct.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()
}
s.Name
or s.Method()
?Test
method is a Bar
pointer, and there is no way to tell whether it is embedded or not.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.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.