简体   繁体   English

go中的结构中的无效递归类型

[英]invalid recursive type in a struct in go

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: 我是Go编程语言的新手,我有一个创建和解释器的任务,但我遇到了以下问题:

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. 根据我的研究,我将父改为* 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". 但是现在当我需要使用var类型的环境创建一个新的环境时,它会得到错误“不能使用fun_Val.ds(类型环境)作为类型*环境中的字段值”。 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. 我试图将此帖中的代码数量保持在一个限制,但如果您需要更多,或有其他问题,请告诉我。

You need to define Environment as: 您需要将Environment定义为:

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. 否则,编译器无法确定Environment结构的大小。 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)}

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.) &是Go的'地址'运营商。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM