How to represent an optional type?

I need a variable that can either have a value or not.

I tried using a pointer but dereferencing a nil pointer is a runtime error.

Surely there must be a way to do this without the variable having a dummy value?

Hey @chimmihc,

Can you show what you are trying to do?

Also, did you try checking the pointer against nil before trying to dereference it, because otherwise, when the pointer has not been set, it will cause an error.

For example, you need to check it first:

if ptr != nil {
    // Do stuff with pointer.
}

Or a better example where using the first p var will cause an error, but the uncommented version won’t fail:

package main

import "fmt"

func main() {
	// var p *int <- Will cause runtime error unless checked against nil (if unset).

	a := 10
	p := &a // <- Will work fine.

	if p != nil {
		fmt.Println(*p)
	} else {
		fmt.Println("p is not set")
	}
}

I am doing something like this.

var x* int

for ... {
    if x != nil {
        // do something with x
        x = nil
    } else {
        *x = blah
    }
}

Ok and what there is causing your runtime error?

For example this works fine:

package main

import "fmt"

func main() {
	var x *int

	for i := 0; i < 5; i++ {
		if x != nil {
			x = nil
		} else {
			x = &i
			fmt.Println(*x)
		}
	}
}

What I’m basically asking is, are you sure that the runtime error is not related to something else? Can you print the stack trace of the error.

Edit: Actually, relooking at your code, the error is probably caused by the fact that you are trying to use this:

*x = something

Instead of using this:

x = &something

Basically you are dereferencing a pointer that is nil and trying to set what x is pointing to (which isn’t pointing to anything when it’s nil) to something, rather than setting the pointer x to the value of something else.

1 Like

Well, that got rid of the runtime error but caused the code to produce completely wrong results.

I couldn’t figure out what was going wrong so in frustration I converted it to a regular variable using a dummy value to represent nothingness and it suddenly worked properly.

I am iterating over the runes in a string and under certain conditions, the variable will hold the value of the previous rune.

Are you sure you’re iterating over the string properly?

For example:

package main

import "fmt"

func main() {
	str := "Hello, World!"

	// Print the runes.
	for _, r := range str {
		fmt.Println(r)
	}

	// Print the index.
	for i := range str {
		fmt.Println(i)
	}
}

Either way, feel free to share what you have tried or what you are trying to actually achieve.

How/when does this happen?

I wonder if you could prevent this wrong value in the first place.

EDIT: Uh, too late :slight_smile:

1 Like

The project is simply a brainfuck interpreter.

Here is the current code: https://pastebin.com/NdihCBFz

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.