invalid recursive type in a struct in go

Go

Go Problem Overview


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.

Go Solutions


Solution 1 - Go

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

Solution 2 - 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.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkfeeneyView Question on Stackoverflow
Solution 1 - GoEvan ShawView Answer on Stackoverflow
Solution 2 - GojnmlView Answer on Stackoverflow