go中结构中的无效递归类型 [英] invalid recursive type in a struct in go

查看:1697
本文介绍了go中结构中的无效递归类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Go编程语言的新手,我有一个创建和解释器的任务,但我遇到了以下问题:

我想定义一个环境as:

 类型环境struct {
父级环境
符号字符串
值RCFAEValue


func(env Environment)lookup(lookupSymbol string)RCFAEValue {
if lookupSymbol == env.symbol {
return env.value
} //如果父母!= nill {
返回env.parent.lookup(lookupSymbol)
}



但是我得到错误无效的递归类型环境。基于我的研究,我改变了家长的类型*环境。但是现在当我需要用var类型的Environment创建一个新的Environment时,它会得到错误不能使用fun_Val.ds(类型Environment)作为类型* Environment的字段值。我创建的环境如下:

  Environment {fun_Val.ds,fun_Val.param,exp.arg_exp.interp(env) } 

我试图将这篇文章中的代码量保持在一个极限,但如果您需要更多,或者有其他问题,请告诉我。

 类型环境struct {
parent * Environment //注意,这现在是一个指针
符号字符串
值RCFAEValue
}

否则编译器没有找出环境结构的大小。指针的大小是已知的,但包含它的东西有多大? (内部结构也包含自身,内部结构也是如此,等等。)



创建环境将如下所示:

 环境{& 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.

解决方案

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)}

这篇关于go中结构中的无效递归类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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