英文:
invalid recursive type in a struct in go
问题
我对Go编程语言还不熟悉,我有一个任务要创建一个解释器,但是我遇到了以下问题:
我想定义一个环境(Environment)如下:
type Environment struct{
parent Environment
symbol string
value RCFAEValue
}
func (env Environment) lookup(lookupSymbol string) RCFAEValue{
if lookupSymbol == env.symbol{
return env.value
} //if parent != nill {
return env.parent.lookup(lookupSymbol)
}
但是我得到了错误信息"invalid recursive type Environment"。根据我的研究,我将parent更改为类型*Environment。但是现在当我需要创建一个类型为Environment的新环境时,它会报错"cannot use fun_Val.ds (type Environment) as type *Environment in field value"。我创建环境的方式如下:
Environment{fun_Val.ds,fun_Val.param,exp.arg_exp.interp(env)}
我试图在这篇文章中尽量保持代码量的限制,但如果您需要更多信息或有其他问题,请告诉我。
英文:
I am new to the Go programming language and I have an assignment to create and interpreter but I am running into the following problem:
I want to define an Environment as:
type Environment struct{
parent Environment
symbol string
value RCFAEValue
}
func (env Environment) lookup(lookupSymbol string) RCFAEValue{
if lookupSymbol == env.symbol{
return env.value
} //if parent != nill {
return env.parent.lookup(lookupSymbol)
}
But I get the error "invalid recursive type Environment". Based on my research I changed the parent to type *Environment. But now when I need to create a new Environment with a var of type Environment it get the error "cannot use fun_Val.ds (type Environment) as type *Environment in field value". I am creating the Environment as follows:
Environment{fun_Val.ds,fun_Val.param,exp.arg_exp.interp(env)}
I am trying to keep the amount of code in this post to a limit but if you need more, or have other questions please let me know.
答案1
得分: 115
你需要将Environment
定义为:
type Environment struct {
parent *Environment // 注意这里是一个指针
symbol string
value RCFAEValue
}
否则编译器无法确定Environment
结构的大小。指针的大小是已知的,但是包含自身的结构有多大呢?(内部结构也包含自身,内部内部结构也是如此,依此类推。)
创建Environment
的方式如下:
Environment{&fun_Val.ds, fun_Val.param, exp.arg_exp.interp(env)}
英文:
You need to define Environment
as:
type Environment struct {
parent *Environment // note that this is now a pointer
symbol string
value RCFAEValue
}
Otherwise the compiler has no way to figure out what the size of the Environment structure is. A pointer's size is known, but how big is something that contains itself? (And the inner struct contains itself as well, as does the inner inner struct, and so on.)
Creating the Environment will then look like:
Environment{&fun_Val.ds, fun_Val.param, exp.arg_exp.interp(env)}
答案2
得分: 2
我希望这样可以解决问题:
Environment{&fun_Val.ds,fun_Val.param,exp.arg_exp.interp(env)}
(&
是 Go 语言中的“取地址”运算符。)
英文:
I hope this should fix the problem:
Environment{&fun_Val.ds,fun_Val.param,exp.arg_exp.interp(env)}
(The &
is the 'address of' operator in Go.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论